在将'char[10]'赋值给'char[50]'时出现了不兼容的类型

问题描述 投票:0回答:1

我总是遇到这样的问题:"'const char [5]'到'char [50]'的赋值中出现了不兼容的类型 "或类似的问题。

#include <stdio.h>
#include <stdlib.h>
struct Lessons{
    char name[50];
    float note;
    int credit;  
}lesson1,lesson2;

int main(){
lesson1.name = "Math";

printf("%s",lesson1.name);

return 0;
}

lesson1.name = "Math";.但我不能解决这个问题。

c arrays string incomplete-type
1个回答
2
投票

你不能使用函数的 = 操作员。 你需要使用 strcpy 库函数。

#include <string.h>
...
strcpy( lesson1.name, “Math” );

2
投票

在C语言中,你不能通过赋值来复制字符串。

你需要使用字符串复制函数(称为 strcpy)的标准库中。

然后

 strcpy(lesson1.name, "Math");

这个规则的唯一例外是用字符串文字或复合文字初始化数组。

例如,在数组中,字词是由函数序幕代码复制的。

int main()
{
     char str[] = "This is string literal";
     struct Lessons lesson3 = {.name = "This is name",};
}

字符被函数序幕代码复制。

© www.soinside.com 2019 - 2024. All rights reserved.