【发布时间】:2019-12-02 23:40:59
【问题描述】:
所以我有一些代码最终将创建一个包含单词和结束句子的标点符号的句子链接列表,但现在我遇到了一个非常特殊的问题:
struct sentence {
char *words[10];
char punc;
struct sentence *next;
};
void split(char *buf, char *split[], size_t max) {
char * token = strtok(buf, " ");
int i = 0;
while (token != NULL) {
split[i] = token;
i++;
token = strtok(NULL, " ");
}
split[i] = NULL;
}
void read_sentence(struct sentence *a) {
printf("> ");
char str[30];
scanf("%[^.!?\n]s", str);
split(str, a->words, sizeof(a->words));
char temp[1];
scanf("%c", temp);
a->punc = temp[0];
a->next = NULL;
}
int main(int argc, char *argv[]) {
struct sentence *a = malloc(sizeof(struct sentence));
read_sentence(a);
printf("\nfirst contains: %s %s%c\n", a->words[0], a->words[1], a->punc);
struct sentence *b = malloc(sizeof(struct sentence));
printf("\nfirst contains: %s %s%c\n", a->words[0], a->words[1], a->punc);
}
每当我运行此代码时,两个打印语句都会产生不同的结果,第一个是正确的,但第二个是空的。我完全不知道为什么会这样。
【问题讨论】: