gpt4 book ai didi

c - 错误 : incompatible types when assigning to type 'char[20]'

转载 作者:行者123 更新时间:2023-12-02 06:00:23 25 4
gpt4 key购买 nike

编码:

struct
{
char firstname[10];
char lastname[10];
char passfail[20];
int score;
}student_mark;

/*Get student details*/

printf("Hello user, please enter your forename\n");
scanf("%s", student_mark.firstname);

printf("\n..and your surname?\n");
scanf("%s", student_mark.lastname);

printf("\n\nHow about your mark out of 10 for the year?\n");
scanf("%d", &student_mark.score);

if (student_mark.score >= 8)
{
student_mark.passfail="DISTINCTION\n";
}
else if (student_mark.score >= 6)
{
student_mark.passfail="PASS\n";
}
else if(student_mark.score <=5)
{
student_mark.passfail="FAIL\n";
}

printf("First name = %s\n", student_mark.firstname);
printf("Last name = %s\n", student_mark.lastname);
printf("Achieved: = %s\n", student_mark.passfail);

return 0;
}

当我运行此代码时,它给了我警告:分配给类型时不兼容的类型 char[20]从类型 char * student_mark.passfail="DISTINCTION\n";
为什么是这样?

最佳答案

您不得使用 =复制字符串时的运算符。您需要使用 strcpy() .

供您引用,student_mark.passfail是一个静态分配的数组。通过使用

student_mark.passfail="DISTINCTION\n";

您要做的是复制字符串的基地址 "DISTINCTION\n"student_mark.passfail多变的。但是,这是不可能的,因为您无法更改静态分配的变量的地址。

OTOH,如果 student_mark.passfail将被定义为 char指针而不是 char数组,那么它本来可以做
student_mark.passfail="DISTINCTION\n";

因为,在那里你会一直使用 student_mark.passfail保存字符串基地址的指针 "DISTINCTION\n" .

关于c - 错误 : incompatible types when assigning to type 'char[20]' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27603641/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com