我的字符指针指向无效值从int正在施放后* [英] My char pointer points to invalid value after being cast from int*

查看:95
本文介绍了我的字符指针指向无效值从int正在施放后*的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我学习C语言编程,我刚开始学习的使用指针阵列。我对这个问题的问题,我希望是输出必须 5 但它的 2 ,任何人都可以请解释一下为什么?

  INT的main(){
   INT ARR [] = {1,2,3,4,5};
   字符* PTR =(字符*)改编;
   的printf(%d个*(PTR + 4));
   返回0;
}


解决方案

假定小端架构,一个int是32位(4字节), INT ARR [] 看起来像这样(在较低的地址至少显著字节十六进制的所有值):

  | 01 00 00 00 | 02 00 00 00 | 03 00 00 00 | 04 00 00 00 | 05 00 00 00

 的char * PTR =(字符*)改编;

现在, PTR 指向第一个字节 - 既然你已经浇注到的char * ,它被视为字符数组开始:

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

然后, *(PTR + 4)访问字符数组的第五元素,并返回相应的字符值:

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

因此​​,的printf()打印 2

在一个大端系统,在每一个字节顺序 INT 颠倒,导致

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

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;
}

解决方案

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

这篇关于我的字符指针指向无效值从int正在施放后*的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆