I am going through C and came to following example which I could not understand from a book “Pointers on C”. Here is the code.
The following declarations are present in one source file:
int a[10];
int *b = a;
But in a different source file, this code is written:
extern int *a;
extern int b[];
int x, y;
...
x = a[3];
y = b[3];
Can someone explain what happens when the two assignment statements are executed? (Assume
that integers and pointers both occupy four bytes.)
When I tried running the code, it gave me segmentation fault for x and when I comment it out and print the value of y, it gave me 0. The concept was some difference between the pointers and arrays.
What happens is undefined behavior, which in your case manifests itself as a segmentation fault.
You most likely want this instead:
And then both of your assignments will fetch
a‘s element at index 3 and put it intoxandy.