void search(char*** p, int numOfWords, int* pNumOfDefArr){
int i, j, index;
char* word = (char*)malloc(WORD_SIZE * sizeof(char));
for (i = 0; i < N; i++) //just clearing the screen
printf("\n");
printf("Hello and thank you for filling Dictionary 1.0 with new words!!\n");
printf("Which word are you looking for??\n");
gets(word);
fix_word(word, 0);
while (strcmp(word, "Exit")){
index = (search_word(p, word, 0, numOfWords - 1, 0));
if (index < 0)
printf("Unknown word!!!!!!\n");
else{
for (j = 0; j < pNumOfDefArr[index]; j++)
printf("%s\n", *(*(p + index) + 1 + j));
}
free(word);
char* word = (char*)malloc(WORD_SIZE * sizeof(char));
printf("Looking for another word?\n");
gets(word);
fix_word(word, 0);
}
printf("Farewell!!\n");
在调试器上,我可以看到第 10 行:while (strcmp(word, "Exit"))
word 的值为
从 "asd" 更改为 "Error reading characters of string." 为什么会这样?
这是 fix_word()
函数的代码:
void fix_word(char* pword, int j){
if (*(pword + j) != '\0'){
if (j == 0 && (*(pword + j) >= 'a' && *(pword + j) <= 'z')){
*pword -= N;
j++;
}
else if (*(pword + j) >= 'A' && *(pword + j) <= 'Z'){
*(pword + j) += N;
j++;
}
else
j++;
fix_word(pword, j);
}
}
最佳答案
这称为作用域。
char* word = (char*)malloc(WORD_SIZE * sizeof(char)); /* 1 */
while (strcmp(word, "Exit")){ /* 1 */
free(word); /* 1 and gone */
char* word = (char*)malloc(WORD_SIZE * sizeof(char)); /* 2 */
}
您已经在两个不同的范围内声明了变量“word”,并且混合使用了它。
如果省略第二个“char *”,一切都会好起来的。
关于c - strcmp 改变字符串的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27968398/