gpt4 book ai didi

C 奇怪的增量行为与 char 指针地址

转载 作者:行者123 更新时间:2023-12-02 04:40:36 24 4
gpt4 key购买 nike

我对 char 指针有一个奇怪的行为。根据我对指针的了解,我应该能够通过向 char 指针的每个指向字符添加一个来移动它,因为 char 是一个字节。然而,情况似乎并非如此,使用增量运算符 +=、++,甚至将 char 指针设置为等于自身加一。这些似乎都没有像人们想象的那样影响指针。如果我只是将一个数字或一个变量添加到我的 char 指针,它会像人们期望的那样完美地工作。

这不起作用:

void getNextWord(FILE * pFile)
{
char * w = (char *)malloc(MAX_WORD_SIZE * sizeof(char *));
char c;
while(c != ' ')
{
c = fgetc(pFile);
if(c != ' ')
{
*(w++) = c;
}
}
*(w++) = '\0';
printf("%s",w);
}

这确实有效:

void getNextWord(FILE * pFile)
{
char * w = (char *)malloc(MAX_WORD_SIZE * sizeof(char *));
int i = 0;
char c;
while(c != ' ')
{
c = fgetc(pFile);
if(c != ' ')
{
*(w + i) = c;
i++;
}
}
*(w + i) = '\0';
printf("%s",w);
}

有人知道为什么会这样吗?

最佳答案

在第一种情况下,每次添加一个字符时都会递增 w,因此它总是指向刚好超出您添加的最后一个字符。当您打印它时,它指向尚未初始化的内存。

char *s = w;  // Save a pointer to the beginning of the string.
while (c != ' ') {
c = fgetc(pFile);
if (c != ' ') {
// Store the character at w, then increment w
// to point at the next available (unused) location.
*(w++) = c;
}
}
// Null-terminate the string, and increment w again.
// Now it points one location beyond the end of the string.
*(w++) = '\0';

// This will print whatever happens to be in the uninitialized memory
// at w. It will continue to print until it encounters a null character
// (or "illegal" memory, at which point it will crash).
printf("%s", w);

// This will work as expected because it prints the characters that
// have been read.
printf("%s", s);

// This will also work because it "resets" w
// to the beginning of the string.
w = s;
printf("%s", w);

关于C 奇怪的增量行为与 char 指针地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20922335/

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