We have
int a[5]={10, 20, 30, 40, 50};
I would like to know how does the following two code segment do?
int *ptr = (int *)(&a+1);
int *t = (int *)(&a -1);
If we have
printf("%d %d %d \n", *(a+1), *(ptr-1), *(t+1));
What should be the result?
All the problems come from the use of
&a, which is a pointer to “an array of five integers”, so that pointer arithmetic (when you think in terms of addresses) gets “scaled” bysizeof(a)(which might e.g. be 20 ifintare 4 bytes and the compiler needs no padding for alignment purposes — reasonable hypotheses, though far from certain of course.So, after
ptris a pointer to int at the memory address “sizeof(a) more than the address a”, andtsimilarly for “sizeof(a) less than the address of a”. Therefore…:Quite possibly a segmentation violation, otherwise
20followed by two completely arbitrary integer values. Sinceptrandtare pointers toint, the address arithmetic scaling for their-1and+1does not compensate that done on&a(the scaling in terms of memory addresses is bysizeof(int), notsizeof(a)!), soptr-1andt+1are pointing to (alleged;-)ints that are respectively “a fewints after the end ofa” and “a fewints before the start ofa“.There’s no way to know whether at those arbitrary addresses there is any memory which the process is allowed to address (whence the possibility for segmentation violatons), and, if any accessible memory is there, what its contents “seen as an
int” might possibly be.Edit: @caf points out that
ptr - 1is not invalid — it correctly points to the last element ofa; so the output (unless there’s a segmentation fault, which @NullUserException thinks is very unlikely but on this point we disagree;-) would start with20 50before the third, “arbitrary” junk. Point is, per the C standard, it is valid to compute (though not to use) the pointer “just one past the end” of an array, and the sizeof an array must be exactly that array’s length time the sizeof its elements (padding is allowed for an element’s type, if needed, and if so it shows in the element’s own sizeof, but not for the array as a whole). Subtle, but important;-).