#include<stdio.h>
int main(){
char a[6],*p;
a[0]='a';
a[1]='b';
a[2]='c';
a[3]='4';
a[4]='e';
a[5]='p';
a[6]='f';
a[7]='e';
printf("%s\n",a);
printf("printing address of each array element");
p=a;
printf("%u\n",&p[0]);
printf("%u\n",p+1);
printf("%u\n",a+2);
return 0;
}
The output is as follows…
anusha@anusha-laptop:~/Desktop/prep$ ./a.out
abc4epfe
printing address of each array element3216565606
3216565607
3216565608
When I declared the array as char a[6] why is it allowing me to allocate a value at a[7]? Does it not need a null character to be appended for the last element?
Also p=a => p holds the address of first element of char array a. I don’t understand how it is correct to place an ‘&’ in front of an address (p[0]). &p[0] means address of address of first element of a which doesn’t make any sense, at least to me.
Why is it printing the correct output?
You have just invoked undefined behaviour. There’s little point in reasoning about writing beyond the bounds of an array. Just don’t do it.
No, that’s perfectly sensible. Your description perfectly describes what is going on.
&p[0]is the same aspwhich is the same asa. When you writep[0]you are dereferencing the pointer. When you then write&p[0]you are taking the address of that variable and thus return to what you started from,p.