i found this exercise online but i can't understand why the result is "aaaaaaaa". can you give me a hand ?
#include <stdio.h>
void a(char * s) {
while(*s++ != '\0')
printf("a");
}
int main() {
int data[5] = {-1,-3,256,-4,0};
a((char *) data);
return 0;
}
This is happening due to the difference in the size of
int
andchar
in C.int
data type takes 4 bytes andchar
takes 1 byte.As the function a() takes
char *
as an argument sos++
will increment 1 byte at a time until it sees a byte with00
hex value.Now the hex value representation of -1 for int is
ff ff ff ff
the hex value representation of -3 for int is
ff ff ff fd
the hex value representation of 256 for int is
00 00 01 00
and so on.
The while loop will compare 1 byte at a time will stop after printing "a" 8 times.
Note: The traversal will be different in the little-endian vs the big-endian machines.
In little endian traversal of 256 will be like
00 -> 01 -> 00 -> 00
.But in big endian traversal of 256 will be like
00 -> 00 -> 01 -> 00
As either way, you are getting
00
first so the endian-ness won't affect the answer.