What does 'char x[]' mean?
I have a struct like this:
struct A
{
char x[];
};
What does it me开发者_如何学JAVAan? When I do something like:
A a;
a.x = "hello";
gcc throws an error saying:
error: incompatible types in assignent of 'const char [6]' to 'char [0u]'
This is a C99 "flexible array member". See here for gcc specifics: http://www.delorie.com/gnu/docs/gcc/gcc_42.html
This structure has a C99 flexible array member. As such it's invalid to declare variables of type struct A
, but you can declare a variable of type struct A *
(pointer to struct A
) and use malloc
to obtain memory for it as:
struct A *a = malloc(sizeof *a + strlen(mystring) + 1);
strcpy(a->x, mystring);
First of all, in C++, you can't have an array of unspecified size. Also, you should use a pointer instead of an array if you want to assign to them string literals:
struct A
{
char* x;
};
char x[] can be read as "x is a pointer to an array of char for which we have not yet allocated the necessary memory". However you either have to specify a contant size (char x[6]) or declare this as a pointer (char* x)
a.x = "hello" does not work because a.x does not point to any memory space you could have allocated. Additionally, the compiler complains about assigning something supposed to be constant (the string) to something that could be changed by the program.
You either have to declare x constant or copy the string manually using a function such as strcpy.
For instance:
struct A
{
char *x;
};
A a;
a.x = new char[6];
strcpy(a.x, "Hello");
精彩评论