Error converting const char to char in struct?
This is a bit written from memory so I apologize if I made a mistake in this posting. I created a struct and wanted to assign a name to it, but I get this error:
error: incompatible types in assignment of
const char[3]' to
char[15]'
For the life of me I tried to understand what exactly is wrong here, I thought a constant char can still be assigned.
# include <stdio.h>
struct type{
char name[15];
int age;
};
main(){
struct type foo;
foo.name = "bar"; //error here
foo.age=40;
printf("Name- %s - Age: %d", foo.name, 开发者_JAVA百科foo.age);
}
name is a fixed-size static buffer. You need to use strcpy or similar functions to assign it a string value. If you change it to be const char* name
instead, then your code should work as-is.
char name[15];
declares an array, which is not assignable in C. Use string copying routines to copy the values, or declare name
as a pointer - char* name;
(here you'd have to worry about memory pointed to still being valid).
You can initialize a struct-type variable as a whole though:
struct type foo = { "bar", 40 };
Here string literal "bar"
(four bytes including zero-terminator) will be copied into the name
member array.
You need to use strcpy
to copy content of strings.
He's confusing an initializer with an assignment.
Once the object is created (the "struct type foo;" line), you have to strcpy into "name").
struct type foo; foo.name = "bar"; //error here <<= The compiler can only do a pointer assignment at this point, which is not valid.
==============
Don't write this crappy code:
strcpy_s(foo.name, 15, "bar");
The following allows you change the length in one place:
strcpy_s(foo.name, sizeof(foo.name), "bar");
精彩评论