c - 在 C 中读取和打印 *char 字符串时的一个特殊错误

标签 c string pointers

我刚刚遇到了一些非常奇怪的事情。当我打印它时,我的 char 字符串(我们称它为 word )结果有额外的字母。
连接的字母取决于:

  1. 正确前缀词的长度。
  2. 单词后的空格数。

我正在解析 word来自line这只是标准输入的一行。我正在使用函数 readWord得到word来自 line :

void readWord(char **linePointer, char **wordPointer){
  char *line  = *linePointer;
  char *word = *wordPointer;
  while (!isEndOfLine(line) && isLowerCaseLetter(*line)){
    *word = *line;
    word++;
    line++;
  }
  word++;
  *word = '\0';
  printf("The retrieved word is: %s.\n", *wordPointer)
  *linePointer = line;
}

我的输入/输出看起来像这样(请注意,我在处理完 readWord 和之间的空格后调用了 insert 函数):

// INPUT 1 :
insert foo
insert ba      // several spaces after 'ba'
// OUTPUT 2:
The retrieved word is foo.
The retrieved word is bas.

// INPUT 1 :
insert foo
insert ba      // several spaces after 'bar'
// OUTPUT 2:
The retrieved word is foo.
The retrieved word is bare.

我在想我要不要分配*word正确,我想我会:

root.word = (char *)malloc(sizeof(char *)); //root is my structure

此外,不太可能与重新分配 word 的一些错误有关字符串,因为它在 readWord() 的开头是完全清楚的功能。

感谢您的帮助。这对我来说确实是一个具有挑战性的错误,我不知道我还能做什么。

更新

事实证明,我实际上在分配/重新分配方面遇到了一些问题,因为:

//INPUT
insert foo//no spaces
  insert bar                //spaces here
//OUTPUT
word variable before calling readWord function: ' '.
The retrieved word is foo.
word variable before calling readWord function: 'insert foo
'.
The retrieved word is bare.

最佳答案

永远不要相信您的输入,因此请检查单词开头的空格。

正如@rpattiso 指出的那样,您将单词增加了太多。

我对你的内存分配有疑问(你没有向我们展示你所有的代码): root.word = (char *)malloc(sizeof(char *)); 为指向 char 的指针分配空间,但不为字符本身分配空间. readWord 可以做到这一点。

以下改编版本应该可以工作(更新):

void readWord(char **linePointer, char **wordPointer){
    char *line  = *linePointer;
    int i;

    while (!isEndOfLine(line) && !isLowerCaseLetter(*line)) line++; // go to begin of word
    *linePointer= line;
    while (!isEndOfLine(line) &&  isLowerCaseLetter(*line)) line++; // go to end of word

    i= line - *linePointer;                     // allocate room for word and copy it
    *wordPointer= malloc((i+1) * sizeof(char));
    strncpy(*wordPointer, *linePointer, i);
    (*wordPointer)[i]= '\0;

    printf("The retrieved word is: %s.\n", *wordPointer);
    *linePointer = line;
}

关于c - 在 C 中读取和打印 *char 字符串时的一个特殊错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29805870/

相关文章:

c - 如何更新结构/记录数据库

c - C 中的 rand() 有多独特?

c - 什么是 CLOCKS_PER_SEC?

c++ - 访问和打印用 new 初始化的 vector 的 vector

C++ 交换指针

c - 可变大小数组,来自函数,从函数调用

c - 在 C 循环中使用字符数组引用

Javascript 字符串比较未显示正确结果

javascript - 当输入不是连续的时将字符串转换为整数

c - 引用指向结构体的指针,该结构体包含指向结构体指针的指针