使用此结构定义:
struct word {
char *cont; //content of the word
char *wsp; //whitespace following the word
int ctr;
};
一句话,我正在尝试编写一个函数来从标准输入中获取第一个单词,然后是所有空格。这里是:
struct word *getword(){
char cont[WORDLIM];
char wsp[WORDLIM];
cont[0] = '\0';
wsp[0] = '\0';
if (peekchar() == EOF) return NULL; //peekchar defined elsewhere as getting a char and ungetc-ing it
REPEAT{ //macro for for(;;)
char c = getchar();
char buf[2];
buf[0]=c;
buf[1]='\0';
if (c == '\n' || c == ' '){
strcat(wsp, buf);
if (peekchar() != '\n' && peekchar() != ' '){
struct word *toret;
toret = malloc(sizeof(struct word));
toret->cont = cont;
toret->wsp = wsp;
toret->ctr = -1;
printf("---%s---\n", toret->wsp); //just for debugging
return toret;
}
continue;
}
}
printf("PANIC PANIC PANIC THIS IS GOING WROOOOONG!!!!!\n");
return NULL;
}
现在有趣的是,我可以在仅用于调试的行中获得正确的空白输出,但是当我尝试访问 getword()->wsp 时,我得到了随机垃圾。更有趣的是, getword()->cont 有效...
我是 C 的新手……我做错了什么?