Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Understand Strlen applied to int array with char * cast

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading