When I run this code:
int arr[3] = {2,3,4};
char *p;
p = (char*)arr;
printf("%d", *p);
p = p+1;
printf("%d", *p);
The output is 2 and 0. The second result is slightly confusing. Could someone explain why this is happening?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Let’s break this down:
Creates an array of 3 integers. Assuming your system is 32bit little endian this is how it looks in memory:
pnow points toarrbut is a pointer tochar*. In other words,ppoints to the02.You are printing as an
intthe location referenced byp. So when you dereferencep(by writing*p) you are accessing thechar(sincepis of typechar*) referenced byp. Which is02.pnow points to the00just after02, becausepischar*. So when you add 1, it will move by1 * sizeof(char) = 1 * 1 = 1byte in memory.You are printing as an
intthe location referenced byp. So when you dereferencep(by writing*p) you are accessing thechar(sincepis of typechar*) referenced byp. Which is00.If you wanted to print
3instead of0you have to change your pointer type toint*instead ofchar*, making the pointer move by1 * sizeof(int) = 1 * 4 = 4bytes in memory.