C - 赋值中的不兼容类型 - 结构和字符数组
C - Incompatible types in assignment - structs and character arrays
好吧,我的情况的要点是,我在尝试初始化我的结构时,在赋值中遇到了不兼容的类型。我对 C 还很陌生,理解指针对我来说是一个很大的挑战,但我已经看过与此错误类似的问题并尝试了不同的修复方法,但到目前为止还没有成功。如果有人能为我解决这个问题,你就是我的英雄。
struct Employee {
char* name[100];
int birth_year;
int starting_year;
};
struct Employee* make_employee(char* name, int birth_year, int starting_year);
int main(){
//some main stuff code
}
struct Employee* make_employee(char* name, int birth_year, int starting_year){
struct Employee* newEmpl = (struct Employee*)malloc(sizeof(struct Employee));
newEmpl->name = name;
newEmpl->birth_year = birth_year;
newEmpl->starting_year = starting_year;
return newEmpl;
}
name = name 行出现赋值错误。我不知道为什么。
另外,如果我用
切换那条线
strcpy(&(newEmpl->name), name);
我得到:
警告:从不兼容的指针类型
传递'strcpy'的参数1
我已经尝试了 2 个小时来寻找问题,但没有成功,所以我想在这里尝试一下。
在您的结构中,更改
char* name[100]; //an array of pointers to character
到
char name[100]; // a character array
然后,在您的 make_employee()
函数中,而不是
newEmpl->name = name; //arrays cannot be assigned
使用
strcpy(newEmpl->name, name); // copy the contains of name to newEmpl->name
或
strncpy(newEmpl->name, name, 99); // limit to 99 elements only + terminating null
备注:
- 请不要投
malloc()
和家人的return值。
- 在使用returned 指针之前,请检查
malloc()
和家人是否成功。
char* name[100];
是指向 char
的指针数组,但是:
char* name;
是指向char
的指针。
这里:
newEmpl->name = name;
您正在尝试将指向 char
的指针分配给数组,但您不能在 C 中将指针分配给数组!事实上,你不能为 C 中的数组分配任何内容。
检查您在程序中使用的类型是否正确。您确定要使用 char *name[100];
而不是 char name[100];
(字符数组)吗?然后要复制一个字符串,请使用 strcpy
或 strncpy
而不是 =
运算符,因为您不能将某些内容分配给数组。
好吧,我的情况的要点是,我在尝试初始化我的结构时,在赋值中遇到了不兼容的类型。我对 C 还很陌生,理解指针对我来说是一个很大的挑战,但我已经看过与此错误类似的问题并尝试了不同的修复方法,但到目前为止还没有成功。如果有人能为我解决这个问题,你就是我的英雄。
struct Employee {
char* name[100];
int birth_year;
int starting_year;
};
struct Employee* make_employee(char* name, int birth_year, int starting_year);
int main(){
//some main stuff code
}
struct Employee* make_employee(char* name, int birth_year, int starting_year){
struct Employee* newEmpl = (struct Employee*)malloc(sizeof(struct Employee));
newEmpl->name = name;
newEmpl->birth_year = birth_year;
newEmpl->starting_year = starting_year;
return newEmpl;
}
name = name 行出现赋值错误。我不知道为什么。 另外,如果我用
切换那条线strcpy(&(newEmpl->name), name);
我得到:
警告:从不兼容的指针类型
传递'strcpy'的参数1我已经尝试了 2 个小时来寻找问题,但没有成功,所以我想在这里尝试一下。
在您的结构中,更改
char* name[100]; //an array of pointers to character
到
char name[100]; // a character array
然后,在您的 make_employee()
函数中,而不是
newEmpl->name = name; //arrays cannot be assigned
使用
strcpy(newEmpl->name, name); // copy the contains of name to newEmpl->name
或
strncpy(newEmpl->name, name, 99); // limit to 99 elements only + terminating null
备注:
- 请不要投
malloc()
和家人的return值。 - 在使用returned 指针之前,请检查
malloc()
和家人是否成功。
char* name[100];
是指向 char
的指针数组,但是:
char* name;
是指向char
的指针。
这里:
newEmpl->name = name;
您正在尝试将指向 char
的指针分配给数组,但您不能在 C 中将指针分配给数组!事实上,你不能为 C 中的数组分配任何内容。
检查您在程序中使用的类型是否正确。您确定要使用 char *name[100];
而不是 char name[100];
(字符数组)吗?然后要复制一个字符串,请使用 strcpy
或 strncpy
而不是 =
运算符,因为您不能将某些内容分配给数组。