Aroic
Aroic

Reputation: 479

Accessing array via pointer in C syntax clarification

This is a fairly basic question that I stumbled across today and want to know the difference between two syntaxes.

Let's say I have a function that assigns a value to an array that is pointed to. I noticed that while both syntaxes compile, the second one below seg faults and the first one runs fine. Why is this?:

Works fine:

foo(int** arr){
    for (i = 0; i < SUM; i++){
        (*arr)[i] = i+1;
    }
}

Seg fault:

foo(int** arr){
    for (i = 0; i < SUM; i++){
        *arr[i] = i+1;
    }
}

Example main:

main(){
    int* _arr;
    arr = (int *)malloc(sizeof(int)*50);//arbitrary
    foo(&_arr);
}

I wrote all this code as an example, if any clarification is needed let me know.

Upvotes: 0

Views: 52

Answers (1)

Jean-Fran&#231;ois Fabre
Jean-Fran&#231;ois Fabre

Reputation: 140158

You're facing operator precedence / priority issues.

  • (*arr)[i] properly dereferences arr into an array, then adds i to get the value.

  • *arr[i] first takes arr+i (uninitialized memory if i>0: you have only 1 array) and tries to read from that invalid pointer: segfault

Upvotes: 1

Related Questions