Understand Strlen applied to int array with char * cast

Advertisements

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 ?

>Solution :

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

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.

Leave a ReplyCancel reply