Reputation:
I am trying to understand how dynamic memory works in C. Suppose I need to allocate memory for some pointer using another function. Is it possible? I tried in the program below, but it keeps crashing in Windows.
void foo(int** x){
*x=(int *)malloc(10*sizeof(int));
int i;
for(i=0; i<10; i++){
*x[i] = 0;
}
}
int main(int argc, char* argv[]){
int *x;
int i;
foo(&x);
for(i=0; i<10; i++){
printf("%d\n",x[i]);
}
return 0;
}
Upvotes: 1
Views: 48
Reputation: 541
The problem is with this line.
*x[i] = 0;
Add parenthesis to the pointer dereference.
(*x)[i] = 0;
This is because x[i] actually means *(x+i). That is, add i to pointer x to get a new pointer and get the value of that memory location.
Now remember that x is a pointer to a pointer. *x[i]
can be more readily be read as **(x+i)
when actually you want *((*x)+i)
.
It might take a bit of thought to get your head around but pointers are easy once you get the hang of it.
Upvotes: 3