The following bit of code…
void foo(char* x)
{
int i;
int len = sizeof(x)/sizeof(x[0]);
printf("len: %d\n", len);
for(i=0; i<len; i++){
printf("i: %d, v: %x\n", i, x[i]);
}
}
…when called as:
char bar[] = {0xDE, 0xAD, 0xBE, 0xEF};
foo(bar);
…outputs:
len: 8
i: 0, v: ffffffde
i: 1, v: ffffffad
i: 2, v: ffffffbe
i: 3, v: ffffffef
i: 4, v: ffffffff
i: 5, v: 7f
i: 6, v: 0
i: 7, v: 0
Not exactly sure if it’s applicable to this but reading through similar posts on SO, it seems to be an alignment issue (I’m on a 64 bit machine).
Any pointers?
Thanks.
This has nothing do to with alignment.
xis a pointer and not an array.sizeof (x)computes the size of the pointer which is 8 bytes on your 64-bit machine.Now it prints
ffffffdeinsteas ofdebecause of integer promotion (sign extension is performed). To avoid theffffffyou can useunsigned chartype instead ofcharor cast theprintfarguments tounsigned intlike this: