简体   繁体   English

在struct上赋值的类型不兼容

[英]Incompatible types in assignment on struct

typedef struct s {
char name[20];
char last_name[20];
int height;
} s_t;

s_t my_s_t;
my_s_t.name = "John";

I get "Incompatible types in assignment" for the last line. 我在最后一行得到“不兼容的作业类型”。 What am I doing wrong? 我究竟做错了什么?

my_s_t.name = "John";

name is a char array. name是一个char数组。 So you can´t directly assign a string literal to it. 因此,您无法直接为其指定字符串文字。 You can use strcpy or similar function to copy the string literal OR declare name as char* . 您可以使用strcpy或类似函数将字符串文字或声明name复制为char*

Options: 选项:

1) 1)

typedef struct s {
char name[20];
char last_name[20];
int height;
} s_t;

s_t my_s_t;
strcpy(my_s_t.name, "John");

2) 2)

 typedef struct s {
    char *name;
    char last_name[20];
    int height;
    } s_t;

    s_t my_s_t;
    my_s_t.name = "John";

You are trying to assign an array. 您正在尝试分配数组。 Arrays are not assignable. 数组不可分配。 This will fail for the same reason 出于同样的原因,这将失败

char a[20];
a = "Hello"; /* Error */

In order to copy data into an array, you have to use a library function, like strcpy 为了将数据复制到数组中,您必须使用库函数,如strcpy

strcpy(a, "Hello");

Meanwhile, it is possible to copy data into an array using core language features (instead of library functions) at the point of initialization , as in 同时,可以在初始化时使用核心语言功能(而不是库函数)将数据复制到数组中,如

char a[20] = "Hello";

In your case you can use aggregate initialization syntax to achieve the same 在您的情况下,您可以使用聚合初始化语法来实现相同的目的

s_t my_s_t = { "John", "Smith", 2 };

As long as you are doing this at the point of initialization, it will work. 只要你在初始化时这样做,它就会起作用。 If you have to do it later, then strcpy is your friend. 如果你以后必须这样做,那么strcpy就是你的朋友。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM