我似乎遇到了分割错误,但我无法弄清楚它发生在哪里或为什么发生。任何输入都会有所帮助。 我基本上是尝试将输入读取为字符,将它们存储到 word 中,直到我点击空格,当我点击空格时,将该单词存储到 wordList 中。 所有这些都必须在不存储在内存中的情况下完成(必须使用动态分配(。
相关代码为:
char* word;
int WFactor = 30;
int WLFactor = 30;
char** wordList;
int wordCount = 0;
int letterCount = 0;
word = (char*)malloc(sizeof(char) * WFactor);
wordList = (char**)malloc(sizeof(char*) * WLFactor);
if( word == NULL ){
free(word);
free(wordList);
fprintf(stderr, "Memory Allocation Failure");
exit(1);
}
if(wordList == NULL){
fprintf(stderr, "Memory Allocation Failure");
exit(1);
}
char cur = '*';
while(cur!=EOF){
if(letterCount == WFactor){
WFactor = WFactor * 2;
word = realloc(word, sizeof(char)*WFactor);
if(word == NULL){
free(word);
free(wordList);
fprintf(stderr, "Memory Re-Allocation Failure");
exit(1);
}
}
cur = getchar();
if(cur!=EOF && cur!= ' '){
putchar(cur);
word[letterCount] = cur;
letterCount++;
}
if(cur == ' '){
if(wordCount == WLFactor){
WLFactor = WLFactor*2;
wordList = realloc(wordList, sizeof(char*)*WLFactor);
if(wordList == NULL){
free(word);
free(wordList);
fprintf(stderr, "Memory Re-Allocation Failure");
exit(1);
}
}
printf("%s", "e");
wordList[wordCount] = word;
wordCount++;
letterCount =0;
word = NULL;
WFactor = 19;
printf("HERE");
word = malloc(sizeof(char)*WFactor);
if(word == NULL){
free(wordList);
fprintf(stderr, "Memory Allocation Failure");
exit(1);
}
}
}
getchar()
返回int
而不是char
。
如果将其结果分配给char
则无法安全地检测 ^EOF'。
修复此更改
char cur = '*';
要成为
int cur = '*';