#include <stdio.h>
#include <string.h>

int main()
{
int n = 0x000000FF, i;
char *p = (char *)&n;
for(i = 0; i < sizeof(int); i++)
printf ("value : %d\n", *(int *)(p + i));
return 0;
}

I'm expecting something like
255
0
0
0
OR
0
0
0
255
depending on the endianess
but i'm getting some garbage values after printing 255 as:
255
-1342177280
-1750073344
-1718112256
Can anyone please share their views why i'm getting this output. Thanks.

Recommended Answers

All 2 Replies

try this

printf ("value : %u\n", *(unsigned char*)(p + i));

This will cast and dereference a byte starting at p + i...You had casting and dereferencing an int starting at p + i which will overflow past n = 0x000000ff.

Thanks for your reply. I donot know how i asked this simple question? :-).

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.