pointers and type casting

my question is when i typecast the integer array then y on incrementing the pointer i get a 0 at the second position.thnx in advance for the help

1
2
3
4
5
6
7
8
9
10
11
12
#include <stdio.h>
int main()
{
    int arr[3]={2,3,4};
    char *p;
    p=(char*)arr;
    printf("%d",*p);
    p=p+1;
    printf("%d",*p);
}



Change line 8 to *p += 1; or *p = *p + 1; if you prefer
thats okay,no prob i'll do it dat way,but i just want to know that y is the second element coming out to b 0
Assuming little-endian and that int is 4 bytes then 2 is probably stored as 00000010 00000000 00000000 00000000 in memory. The original char pointer p will point to the first byte which is 00000010 and that will be interpreted as the value 2. After incrementing the pointer p it will point to the second byte which are all zero bits so it will be interpreted as the value 0.

1
2
3
00000010 00000000 00000000 00000000
^        ^
p        p+1
Last edited on
It maybe easier to understand if you initialise and print the values in hexadecimal. The reason for that is that a single byte of memory can be represented by a pair of hexadecimal digits.

1
2
3
4
5
6
7
8
9
10
11
#include <stdio.h>

int main()
{
    int arr[3] = {0x12345678, 3, 4};

    char *p =  (char*) arr;

    for (unsigned int i=0; i<sizeof(arr); i++)
        printf("%02x ", *p++);
}


Output:
78 56 34 12 03 00 00 00 04 00 00 00


Actual output is system dependent.

in this case, the low-order bytes of the integer are stored before the higher-order bytes. See http://en.wikipedia.org/wiki/Endianness
Last edited on
thnx a lot that was really helpful!
Topic archived. No new replies allowed.