未检测到NULL值

时间:2014-03-12 03:46:06

标签: c

我似乎无法理解这里有什么问题,有人可以帮帮我吗? 每次程序运行时,它都会输出句子的所有单词。然后它尝试复制第11个字(只有10个),它不应该是因为它应该检测到NULL。我的TA无法弄清楚出了什么问题,所以要么他没有尝试过,要么比我之前的想法更复杂。

#include <stdio.h>
#include <string.h>

struct myWord{
    char Word[21];
    int Length;
};

int main(){
    struct myWord WordList[21];
    char myString[] = "the cat in the hat jumped over the lazy fox";
    char* temp;
    int n = 0, i;

    temp = strtok(myString, " ");
    while (WordList[n].Word != NULL){
        printf("%s\n", temp);
        strcpy(WordList[n].Word, temp);
        temp = strtok(NULL, " ");
        WordList[n].Length = strlen(temp);
        n++;
    }
    printf("works!\n");
    return 0;
}

2 个答案:

答案 0 :(得分:2)

您正在检查WordList[n].WordNULL,这是没有意义的,因为此时它未初始化。您还要将Length设置为下一个字符串&#39;长度,因为您在致电strtok之前重新运行strlen(temp)。尝试这样的事情:

temp = strtok(myString, " ");
while (temp != NULL) {
    printf("%s\n", temp);
    strcpy(WordList[n].Word, temp);
    WordList[n].Length = strlen(WordList[n].Word);
    temp = strtok(NULL, " ");
    n++;
}

此外 - 根据此代码的使用,请注意缓冲区溢出。您应该检查n是否超过21(您拥有的WordList项的数量),temp的长度不超过21(空间)每个struct myWord都有一个Word)。 strncpy可能特别有助于后者。为清晰起见,我可能也#define最大尺寸:

#include <stdio.h>
#include <string.h>

#define MAXLEN 21

struct myWord {
    char Word[MAXLEN];
    int Length;
};

int main() {
    struct myWord WordList[MAXLEN];
    char myString[] = "the cat in the hat jumped over the lazy fox";
    char* temp;
    int n = 0;

    temp = strtok(myString, " ");
    while (n < MAXLEN && temp != NULL) {
        printf("%s\n", temp);
        strncpy(WordList[n].Word, temp, MAXLEN);
        WordList[n].Word[MAXLEN - 1] = 0; // strncpy might not null terminate
        WordList[n].Length = strlen(WordList[n].Word);
        temp = strtok(NULL, " ");
        n++;
    }
    printf("works!\n");
    return 0;
}

答案 1 :(得分:0)

实际上,你应该在while循环中测试temp!= NULL。另外,你应该交换

    temp = strtok(NULL, " ");
    WordList[n].Length = strlen(temp);

    WordList[n].Length = strlen(temp);
    temp = strtok(NULL, " ");

如果你想要正确的单词长度

temp = strtok(myString, " ");
while (temp != NULL)
{
    printf("%s\n", temp);
    strcpy(WordList[n].Word, temp);
    WordList[n].Length = strlen(temp);
    temp = strtok(NULL, " ");
    n++;
}