Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C pointer anomaly, please explain

I have a function, the basic idea of the function is to change what a points to. The first version works however the second version does not.

Could someone please help me to understand what is going on here?

// this works
void swap(int **a) {
    int *temp = malloc(sizeof(int) * 3);
    temp[0] = 0;
    temp[1] = 1;
    temp[2] = 2;
    *a = temp;
}

// this does not
void swap(int **a) {
    *a = malloc(sizeof(int) * 3);
    *a[0] = 0;
    *a[1] = 1; // seg fault occurs on this line
    *a[2] = 2;
}

I am calling the function like so

int main() {
   int b[] = {0,1};
   int *a = b;

   swap(&a);

   return 0;
}

Also, both functions do not belong to the same file at the same time.

like image 476
robbmj Avatar asked Mar 25 '13 18:03

robbmj


1 Answers

The precedence of [] is higher than * (in fact, [] has the highest precedence in C). That means your expression is *(a[0]) rather than (*a)[0] as you intended.

like image 187
Ben Jackson Avatar answered Nov 15 '22 07:11

Ben Jackson