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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With