gpt4 book ai didi

c - 通过*指针分配后,相邻的内存块将被零填充。为什么?

转载 作者:行者123 更新时间:2023-12-02 09:16:44 25 4
gpt4 key购买 nike

我正在通过一本旧书“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 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;
}

所以,输出是:

AAAA
0000

为什么最后 4 个字节为零?

附注已经得到答案:类型 long 在 x64 机器上是 8 个字节,而我不善于观察。惊讶 StackOverflow 是多么好的东西。谢谢你们。

最佳答案

您的 long 可能是 64 位大。它可以与 int32_t 指针一起使用(在我的电脑上):

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

但严格来说,这种类型双关是严格别名违规(这使得您的程序未定义)。 memcpychar 逐个char 从 32 位整数复制,或 unions (最安全,以防万一决定开始动态分配对象),应该可靠地做到这一点:

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

关于c - 通过*指针分配后,相邻的内存块将被零填充。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46472314/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com