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

Casting from int array to char pointer in C

int v_1[10] = { -1,1000,2 };

int a;

a = strlen(((char*)v_1 + 1));

I’m having trouble understanding why the ‘a’ variable is equal to 5 in this particular case.

I’m also struggling to grasp the behavior of the typecasting to char*. I don’t undrstand if the are some calculation for the typecasting that i’m missing because i cannot get 5 in any way.

I attempted to modify the values in the array, but I can’t discern what leads to the resulting outcome.

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 am working on a Windows platform.

>Solution :

The value of a depends a lot on what system you run this on. Presumably in this case, you’re using a system where sizeof int is equal to 4, and integers are stored in little-endian.

A simple program can show you the contents of your data in hex:

#include <stdio.h>

int main(void)
{
    int v_1[10] = { -1,1000,2 };
    for (size_t i = 0; i < sizeof v_1; i++) {
        if (i > 0 && i % 4 == 0) printf(" "); // add a space every 4 bytes
        printf("%02hhx", *((char*)v_1 + i));
    }
    printf("\n");
}

Output (on a system with 4-byte little-endian integers):

ffffffff e8030000 02000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000

Now, your question is about why strlen(((char*)v_1 + 1)); is equal to 5. To answer that, look at the output again:

ffffffff e8030000 
  ^
  This position is (char*)v_1 + 1

You can see that strlen is going to step over five bytes (ff ff ff e8 03) before reaching a NUL byte, which is what delimits the end of a string. And so that is why, on your system, you get the value 5.

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