Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

My char pointer points to invalid value after being cast from int*

Tags:

arrays

c

pointers

I am learning C programming language, I have just started learning arrays with pointers. I have problem in this question, I hope the that output must be 5 but it is 2, Can anyone please explain why?

int main(){    int arr[] = {1, 2, 3, 4, 5};    char *ptr = (char *) arr;    printf("%d", *(ptr+4));    return 0; } 
like image 473
Mayank Tiwari Avatar asked Jul 02 '13 11:07

Mayank Tiwari


People also ask

What happens when you cast a char pointer to an int pointer?

When casting character pointer to integer pointer, integer pointer holds some weird value, no where reasonably related to char or char ascii code. But while printing casted variable with '%c', it prints correct char value. Printing with '%d' gives some unknown numbers.

Can you cast an int pointer to a char pointer?

No, it changes the default interpretation of what the pointer points to. When you read from an int pointer in an expression *myIntPtr you get back the content of the location interpreted as a multi-byte value of type int .

Is char * a pointer?

The type of both the variables is a pointer to char or (char*) , so you can pass either of them to a function whose formal argument accepts an array of characters or a character pointer.

Can a char pointer hold address of a int variable?

Its address has type int * , not char * . You need to declare it to be char if you want a compatible address. And '495' doesn't make sense as a character constant, at least not for assigning to a char . *ptr='495'; is undefined behaviour ...


1 Answers

Assumed a little endian architecture where an int is 32 bits (4 bytes), the individual bytes of int arr[] look like this (least significant byte at the lower address. All values in hex):

|01 00 00 00|02 00 00 00|03 00 00 00|04 00 00 00|05 00 00 00 
char *ptr = (char *) arr; 

Now, ptr points to the first byte - since you have casted to char*, it is treated as char array onwards:

|1|0|0|0|2|0|0|0|3|0|0|0|4|0|0|0|5|0|0|0  ^  +-- ptr 

Then, *(ptr+4) accesses the fifth element of the char array and returns the corresponding char value:

|1|0|0|0|2|0|0|0|3|0|0|0|4|0|0|0|5|0|0|0          ^          +-- *(ptr + 4) = 2 

Hence, printf() prints 2.

On a Big Endian system, the order of the bytes within each int is reversed, resulting in

|0|0|0|1|0|0|0|2|0|0|0|3|0|0|0|4|0|0|0|5          ^          +-- *(ptr + 4) = 0 
like image 83
Andreas Fester Avatar answered Sep 19 '22 16:09

Andreas Fester