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;
}
2

There are 2 answers

0
Ankur Gautam On

This is happening due to the difference in the size of int and char in C. int data type takes 4 bytes and char takes 1 byte.

As the function a() takes char * as an argument so s++ will increment 1 byte at a time until it sees a byte with 00 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.

0
August Karlstrom On

The output is aaaaaaaa (eight a:s) if the size of int is four bytes and int:s are stored using two's complement. In the numbers -1 and -3, all bytes are non-zero, so eight a:s are printed. In the number 256, the least significant (and the most significant) byte is zero so this halts the while loop.

If you print the array byte per byte with

#include <stdio.h>

int main(void)
{
    int data[5] = {-1, -3, 256, -4, 0}, i;
    const char *p;

    p = (char *) data;
    for (i = 0; i < sizeof (data); i++) {
        printf(" %d", p[i]);
    }
    printf("\n");
    return 0;
}

you get

-1 -1 -1 -1 -3 -1 -1 -1 0 1 0 0 -4 -1 -1 -1 0 0 0 0

Here you can see that the ninth number is zero.