有了这个结构定义:
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;
}
现在有趣的是,我可以在 just for debugging 行中获得正确的空白输出,但是当我尝试访问 getword()->wsp 时,我得到随机垃圾。更有趣的是,getword()->cont 工作...
我是 C 语言的新手...我做错了什么?
最佳答案
您正在返回指向超出范围的内存的指针。
您动态分配一个struct word
,但实际的字符保存在wsp
数组中。一旦您的函数返回,它就超出了范围,因此可以包含任何内容。
关于c - 我用于获取单词的奇怪的非工作 C 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14590867/