Hi all! I just have quick, possibly stupid question....
is it possible to do the following:
int func(){
int *pointer;
foo(pointer);
}
int foo(int *pointer){
pointer = (int*)malloc(10 * sizeof(int));
}
do I just have the syntax wrong or is this illegal?
This is completely valid code but I'm guessing it does not do what you
want it to do. Just to keep things a little easier to discuss, here is
your code with different variables:
#include <stdlib.h>
void foo(int *);
int main(void)
{
int *p;
foo(p);
return 0;
}
void foo(int *q)
{
q = malloc(10*sizeof int);
}
First, I #include <stdlib.h> when using malloc. Second, I do not return
anything from foo so it is defined as returning void. Third, I do not cast
the result of malloc, which hides the fact you forgot to #include
<stdlib.h>.
Now, here is an explanation of what the code does:
The first line of main will create a variable called p. This variable will
exist somewhere. The contents of this variable will be some random value.
The second line of main we pass this random value to the function foo.
When we reach the function foo it creates a variable called q and assigns
q with the random value p holds. On the first line of foo we change the
value of q to the memory location returned by malloc. The variable q (not
p) now holds a valid memory location (assuming malloc was successful). I
then return to main. The variable q is now out of scope and disappears.
The memory it points to is lost.
Important thing to note is that at no time was the variable p assigned any
value. You are probably assuming that by altering q, a COPY of p, you are
some how altering p. Not so.
What you need to do is pass in the address of p (&p) and then have foo
accept (int **q). Any change to *q will be a change to p. This is because
q is a pointer to p thus *q is p.