1

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;

}
0

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.