分配中的类型不兼容

Mua*_*ani 2 c

我在C中编写一些代码:

int main(){
    char guess[15];
    guess = helloValidation(*guess);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我的功能是:

char[] helloValidation(char* des) {
    do {
        printf("Type 'hello' : ");
        scanf("%s", &des);
    }while (strcmp(des, "hello") != 0);
        return des
}
Run Code Online (Sandbox Code Playgroud)

但它给了我这个错误:

incompatible types in assignment 
Run Code Online (Sandbox Code Playgroud)

Uns*_*ned 8

guess数组由函数本身修改.然后,您尝试重新分配数组指针guess,从而导致错误.更不用说错误地尝试引用*guess或使用&des不正确.我建议你阅读C指针/数组概念.

#include <stdio.h>
#include <string.h>

char* helloValidation(char* des) {
    do {
        printf("Type 'hello' : ");
        scanf("%s", des);
    } while (strcmp(des, "hello") != 0);
    return des;
}

int main() {
    char guess[15];
    helloValidation(guess);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

  • @JimBalter - 你在哪里得到这个想法没有方法应该是无效的?无论如何,我并没有试图重写OP的代码,只是纠正错误.[这个问题](http://stackoverflow.com/q/3561427/629493)和[答案](http://stackoverflow.com/a/3561465/629493)有很好的例子,可以返回参数非常有用(例如消除了无关的临时变量). (2认同)