[英]c char to int pointer
#include<stdio.h>
int main(void)
{
int arr[3] = {2, 3, 4};
char *p;
p = (char*)arr;
printf("%d", *(int*)(p+1));
return 0;
}
我在指针上做了这个问题。 自从char *转换为int *以来,我期望输出为某些垃圾值,但输出始终为50331648,这很奇怪。 请解释
编辑:我在某些网站上阅读了此输出问题,因此需要根据给定的说明进行输出
您正在执行的操作是未定义的行为。
假设sizeof(int)
为4
小端系统
在小端系统中, arr
的内存布局为:
arr
+----+----+----+----+----+----+----+----+----+----+----+----+
| 02 | 00 | 00 | 00 | 03 | 00 | 00 | 00 | 04 | 00 | 00 | 00 |
+----+----+----+----+----+----+----+----+----+----+----+----+
使用时:
char* p = arr;
p p+1
| |
v v
+----+----+----+----+----+----+----+----+----+----+----+----+
| 02 | 00 | 00 | 00 | 03 | 00 | 00 | 00 | 04 | 00 | 00 | 00 |
+----+----+----+----+----+----+----+----+----+----+----+----+
如果将p+1
解释为int*
,并将该位置处的对象评估为int
,则会得到:
+----+----+----+----+
| 00 | 00 | 00 | 03 |
+----+----+----+----+
在小端系统中,该数字为
0x03000000
等于50331648
,这是您获得的输出。
大端系统
在大端系统中, arr
的内存布局为:
arr
+----+----+----+----+----+----+----+----+----+----+----+----+
| 00 | 00 | 00 | 02 | 00 | 00 | 00 | 03 | 00 | 00 | 00 | 04 |
+----+----+----+----+----+----+----+----+----+----+----+----+
评估*(int*)(p+1)
时得到的数字是:
+----+----+----+----+
| 00 | 00 | 02 | 00 |
+----+----+----+----+
等于0x0200
,即512。
很明显,为什么您执行的操作是未定义的行为。
您将arr声明为int,将p声明为char 。 您的程序将无法使用现代编译器进行编译。 您尝试在其中分配不同类型的指针,这种方法是错误的。
我认为这是您需要的:
#include<stdio.h>
int main(void) {
int arr[3] = {2, 3, 4};
char *p;
p = (char*)arr;
printf("%d", *(int*)(p+1));
return 0;
}
输出(垃圾):
50331648
这是您的代码的逐行说明,最后说明了为什么获得该输出
//assuming 32-bit machine
int arr[3] = {2, 3, 4}; //arr is a pointer to the first element which is an int 2 with a memory size of 4 bytes (int = 4 bytes)
char *p; //p is declared a pointer to a char implying it points to a 1 byte memory size (char = 1 byte)
p = (char*)arr; /* p now points to the first element of the array but actually this happens by luck.
here is why: (char*)arr will attempt to cast the int pointer to a char pointer,
in other words, asking it to present whatever took 4bytes to be presented in 1 byte
which will overwrite the least significant bytes. but since numbers are stored in reverse order,
it will overwrite only zeros causing no problem.*/
printf("%d", *(int*)(p+1)); /* p is still a char pointer holding memory address of 2 in the array.
casting that to int* will add extra bytes from memory. so finally what you're getting is
garbage number which I think is the virtual memory limit, (48 Gb *1024 *1024 = 50331648 Kb)*/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.