0

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.

3
  • 1
    operator precedence between * and [] Commented Feb 21, 2017 at 21:01
  • 1
    Why are you passing and using a double pointer in the function? a single pointer: void foo(int *arr) is enough. Commented Feb 21, 2017 at 21:02
  • could be useful if the malloc is done within the function. otherwise you're right, it's just food for segv. Commented Feb 21, 2017 at 21:05

1 Answer 1

1

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

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

2 Comments

After I asked this question and got to thinking more about it that seemed like the answer, but I figured I'd post anyways just to make sure. Thanks!
@TMartin To put it another way, *arr[i] has the same meaning as *(arr[i]). Sounds like you got it :)

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.