Having this:
#include <stdio.h>
#include <stdlib.h>
struct Test { char c; } foo;
int main (void) {
struct Test **ar;
ar=malloc(16);
*(ar+1) = &foo;
ar[1]->c = 'c'; //this work
(*(*ar+1)).c = 'c'; //this does't work
return 0;
}
//(**(ar+1)).c='c'; --> first case
Why the above works only the variant with array entry and not pointer dereference?
struct Test { char c; } foo;
int main (void) {
struct Test **ar;
ar=malloc(16);
*ar=malloc(0);
*(ar+1) = &foo;
//(**(ar+1)).c='c';
(*(*ar+1)).c='c'; // NOW IT WORKS --> second case
printf("%c\n", (*(*ar+1)).c); //prints 'c'
return 0;
}
Now even allocated 0 bytes, that doesnt matter since I just want an address provided by OS in order to have the first element initilalized
question: how does pointer arithmetic works in both cases? As I understand the them:
1) first In order to get to lvalue of struct Test, the pointer goes directly from the pointed address by ar to the lvalue by **ar - sizeof(struct Test**)
2) in second case, the pointer does have initialized the first member ar[0], so it starts here *ar and goes to the lvalue by *ar - sizeof(struct Test*).
But both pointers have same size sizeof(struct Test**) == sizeof(struct Test*), and therefor shouldn't be difference in arithmetic, or I am missing somehting?
'*'has higher precedence than'+'so what is happening with(*(*ar+1)).c?ar[1][0].c = 'c';and "this doesn't work" isar[0][1].c = 'c', which doesn't work because you never set a value forar[0]. In the second one you cause undefined behaviour but sometimes that manifests itself as appearing to do what you expected