Your program invokes undefined behavior. It assumes that a pointer will fit into an int
, which isn't required. Usually pointers will fit on Unix boxes and fail on Windows; but you should use an appropriate integer type, such as intptr_t
from stdint.h
if you need to do such conversions. Note that strictly speaking the integer must be cast back to a pointer type before being passed to printf
.
Using a pointer type to printf
and a large enough integral type results in correct behavior: http://ideone.com/HLExMb
#include <stdio.h>
#include <stdint.h>
int main(void)
{
char ar[10][10];
strcpy(ar[1], "asd");
strcpy(ar[2], "fgh");
intptr_t test[2];
test[1] = (intptr_t)ar[1];
printf("%s %x | %s %x\n\n", ar[1], ar[1], (char*)test[1], (char*)test[1]);
return 0;
}
Note though that casting pointers into integral types is generally frowned upon and is likely to result in program bugs. Don't go there unless you absolutely need to do so for one reason or another. When you're starting out in C it is unlikely that you'll ever need to do this.