通过*指针分配后,相邻的内存空间将填充为零。为什么?

Pol*_*s.A 2 c

我正在阅读一本旧书“ The C Programming Language”来学习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;
}
Run Code Online (Sandbox Code Playgroud)

因此,输出为:

AAAA
0000
Run Code Online (Sandbox Code Playgroud)

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

PS已经得到了答案:在x64机器上,long类型是8个字节,我很ob昧。惊讶StackOverflow是一件好事。感谢大伙们。

PSk*_*cik 5

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

#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;
}
Run Code Online (Sandbox Code Playgroud)

但严格来说,这种类型修饰是一种严格的混叠冲突(这会使您的程序不确定)。memcpy或从32位整数进行char逐个char复制,或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;
}
Run Code Online (Sandbox Code Playgroud)