Casting from int array to char pointer in C

70 views Asked by At
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.

I am working on a Windows platform.

1

There are 1 answers

0
paddy On BEST ANSWER

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.