用 C 指针弄乱了一点,我遇到了一个相当奇怪的行为。
考虑以下代码:
int
main ()
{
char charac = 'r';
long long ptr = (long long) &charac; // Stores the address of charac into a long long variable
printf ("[ptr] points to %p containing the char %c\n", ptr, *(char*)ptr);
}
在 64 位架构上
现在,当为 64 位目标架构编译时(编译命令:)gcc -Wall -Wextra -std=c11 -pedantic test.c -o test
,一切都很好,执行给出
> ./test
[ptr] points to 0x7fff3090ee47 containing the char r
在 32 位架构上
但是,如果编译的目标是 32 位拱门(使用编译命令 : gcc -Wall -Wextra -std=c11 -pedantic -ggdb -m32 test.c -o test
),则执行会给出这个奇怪的结果:
> ./test
[ptr] points to 0xff82d4f7 containing the char �
现在最奇怪的部分是,如果我printf
将前面代码中的调用更改为printf ("[ptr] contains the char %c\n", *(char*)ptr);
,执行会给出正确的结果:
> ./test
[ptr] contains the char r
这个问题似乎只出现在 32 位架构上,我无法弄清楚为什么printf
调用更改会导致执行行为不同。
PS:可能值得一提的是,底层机器是x86 64位架构,但是使用.in-m32
选项gcc
。