【问题标题】:C Weird incremental behavior with char pointer addressC char 指针地址的奇怪增量行为
【发布时间】:2014-01-04 14:43:52
【问题描述】:

我对 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);
}

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

【问题讨论】:

  • 自增运算符实际上是在做你所期望的。问题出在你最后的printf 语句中。

标签: c pointers char


【解决方案1】:

在第一种情况下,每次添加字符时都会增加 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);

【讨论】:

  • 我现在明白了。那么如果我从 char 地址中减去,那么我就可以正确打印它了?
猜你喜欢
  • 2021-07-28
  • 2013-03-31
  • 2020-11-28
  • 2012-05-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-22
  • 1970-01-01
相关资源
最近更新 更多