c - strcmp 改变字符串的值

标签 c

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/

相关文章:

c - 为什么 -0x80000000 + -0x80000000 == 0?

c - 'Segmentation fault (core dumped) '是什么原因

c - 将带有数组的结构传递给多个线程

c - 在 task_struct (sched.h) 中添加新变量破坏鼠标 LINUX 内核

c - C中并行计算的最佳方法

c - GCC 抽象语法树

c - GTK 3.0 给出编译器错误 "Only <gdk/gdkh> can be included directly"

在C中将int数组更改为float数组

c - 在c中使用函数和结构有很多错误

c++ - 跨平台编程