I executed this code after compiling in codeblocks:-
#include <stdio.h>
int main()
{
char arr[]="HELLO";
int a=arr;
return printf("...%s ,%s\n",arr,&a+1);
}
I got this output:-
…HELLO,HELLO
when I changed &a to a,printf returned -1.
I am not able to sort out this address logic ,please help.
(A friend gave me this code and asked its explanation, and I am not able to find it). So I would like to know why..
Thanks
You are telling
printfto expect a string, but you are giving it the address of anint(&a). This invokes undefined behaviour, so anything could happen.[In practice, what’s probably happening is that the compiler places
adirectly belowarron the stack. So&a+1ends up equal in value to&arr.printfthen reinterprets that address as a pointer-to-char, and so ends up printingHELLO. If the compiler happened to arrange the stack differently, you’d observe different behaviour.]