Understand Strlen applied to int array with char * cast

146 Views Asked by At

I'm currently stuck on this problem.

I have thefollowing code:

    int v[10] = {-1, 1000, 2};
    
    int a;
    
    a = strlen((char *)v+1);
    
    printf("strlen result for (char *) v+1: %d\n", a);

I cannot undestand why the final result is always 5 on a little endian "machine". According to strlen documentation, the char * cast in this situation should return 4.

I tried also in online compiler and other machines but the result remains the same. What am I missing ?

3

There are 3 best solutions below

0
Harlan Wei On BEST ANSWER

You should not use strlen on an int array. The function's name already suggested it should only be used on legally formed C strings.

That being said, for the reason of studying, array v's memory layout looks something like this on a little-endian machine:

    ff ff ff ff e8 03 00 00 02 00 00 00 (00 onwards)
low 0>-^^----<0 1>-------<1 2>-------<2 3> ...----<9 high

Since you are calling strlen((char *)v + 1), the computation starts at the location I marked with ^. There're 5 non-zero elements (ff, ff, ff, e8, 03), so the result is 5, not 4. Remember 1000 == 0x3e8.

0
stark On

Most likely the bytes in V are represented as:

0xff, 0xff, 0xff, 0xff, 0xe8, 0x03, 0x00, 0x00,  ...

So after skipping the first byte (not the first int, since you cast to char *) there are 5 bytes before the first '\0' character.

1
Aethiopis II ben Zahab On

This little demo can help you clarify how bytes are ordered in little-endian machine (presuming every thing is as written above):

char* z = (char*)v + 1;
for (int i = 0; i < 10; i++)
    printf("%02x ", (uint8_t)z[i]);

the print out should be like this: ff ff ff e8 03 00 00 02 00 00 (like Harlan Wei showed above).

this little snippet can also help you see how bytes are stored in big-endian machines too. So mere counting should give you 5 not 4 as strlen(...) was trying to say.