ankur
anshu
si^CPress any key to continue . . .
我在指针上做了这个问题。我期望输出是一些垃圾值,因为从char *转换为int *但输出总是50331648,这很奇怪。请解释
编辑:我在某个网站上阅读了这个输出问题,因此需要根据给定的说明进行输出答案 0 :(得分:7)
您正在做的是未定义的行为。
假设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。
很明显,为什么您正在执行的操作是未定义的行为。
答案 1 :(得分:1)
您将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
答案 2 :(得分:0)
以下是对代码的逐行说明,最后解释了为什么要获得该输出
//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)*/