C 通过*指针赋值后,相邻内存段将被零填充。为什么?
我正在用一本旧书《C编程语言》学习C语言,目前正在试验指针C 通过*指针赋值后,相邻内存段将被零填充。为什么?,c,C,我正在用一本旧书《C编程语言》学习C语言,目前正在试验指针 #include <stdio.h> int main (void) { // init string char s[8] = "ZZZZZZZ"; // it goes: Z Z Z Z Z Z Z \0 long *p; // make pointer refering to the same adress as s p = s; // but
#include <stdio.h>
int
main (void)
{
// init string
char s[8] = "ZZZZZZZ";
// it goes: Z Z Z Z Z Z Z \0
long *p; // make pointer refering to the same adress as s
p = s; // but declared long for modifying 4 bytes at once
*p = 0x41414141; // and assign hexadecimal constant equal to 65 65 65 65
// expect output to be: AAAAZZZ
printf ("%s\n", s);
// but get the next: AAAA
// wrote the following line to find out what's wrong with last 4 chars
printf ("%i%i%i%i\n", s[4], s[5], s[6], s[7]);
// and those appear to become zero after messing with first 4 ones
return 0;
}
为什么最后4个字节是零
PS.已经得到了答案:在x64机器上,type long是8字节,我没有观察到。我很惊讶这是一件多么好的事情。谢谢大家。您的
长
可能是64位大。它可以与int32\t
指针一起工作(在我的电脑上):
您可以尝试设置不同的值,您将看到体系结构是little endian:
#include <stdio.h>
int main (void)
{
char s[8] = "ZZZZZZZ";
// it goes: Z Z Z Z Z Z Z \0
long *p;
p = (long *)s;
*p = 0x41424344; // A B C D
printf ("%s\n", s);
return 0;
}
添加
printf(“sizeof(long)=%zd\n”,sizeof(long))代码>在程序中的某个位置,然后再次运行它。这印的是什么?(我敢打赌它打印的是“sizeof(long)=8”。)您应该知道,因为您是在从一本旧书中学习,所以您正在编写的代码现在被认为是不正确和糟糕的样式。哎呀。。这本书确实很老了,long的大小现在也依赖于实现,并且在32位和64位之间变化,因为现代CPU扩展了64位体系结构。我做对了吗?sizeof(long)
一直依赖于实现,但我认为是的,这就是问题所在。如果long
实现为64位类型,那么您将得到预期的结果。在32位系统上,您应该获得ZZZZ
。感谢您的帮助等一下。。不是long=0x4141应该给出“\0\0\0\0AAAA”而不是“AAAA\0\0\0\0”?@Polazhinets.A您使用的是一个小小的endian体系结构。小结局是第一位的。。现在我看到它确实应该是这样,为了兼容的结果(它的年轻32位peace仍然发现它位于指针指向的地方,下面的4个字节用作存储更高部分的扩展)
#include <stdio.h>
#include <stdint.h>
int
main (void)
{
// init string
char s[8] = "ZZZZZZZ";
// it goes: Z Z Z Z Z Z Z \0
int32_t *p; // making pointer refering to the same adress as s
p = (int32_t*)s; // but declared as long for modifying 4 bytes at once
*p = 0x41414141; // and assign hexadecimal constant equal to 65 65 65 65
// expect output to be: AAAAZZZ
printf ("%s\n", s);
// but get the next: AAAA
// wrote the following line to find out what's wrong with last 4 chars
printf ("%i%i%i%i\n", s[4], s[5], s[6], s[7]);
// and those appear to become zero after messing with first 4 ones
return 0;
}
#include <stdio.h>
#include <stdint.h>
#include <string.h>
int
main (void)
{
// init string
char s[8] = "ZZZZZZZ";
// it goes: Z Z Z Z Z Z Z \0
int32_t src = 0x41414141;
memcpy(s, &src, sizeof(src));
// expect output to be: AAAAZZZ
printf ("%s\n", s);
// but get the next: AAAA
// wrote the following line to find out what's wrong with last 4 chars
printf ("%i%i%i%i\n", s[4], s[5], s[6], s[7]);
// and those appear to become zero after messing with first 4 ones
return 0;
}
#include <stdio.h>
int main (void)
{
char s[8] = "ZZZZZZZ";
// it goes: Z Z Z Z Z Z Z \0
long *p;
p = (long *)s;
*p = 0x41424344; // A B C D
printf ("%s\n", s);
return 0;
}
*p = 0x0000000041424344; // /0 /0 /0 /0 A B C D