I tried to compile the following code, but the compiler wouldn't doing because " * is illegal for a struct" is that true?
struct String {
int length;
int capacity;
unsigned check;
char ptr[0];
} String;
void main(){
char *s;
String *new_string = malloc(sizeof(String) + 10 + 1);
}
Either use a typedef:
typedef struct String {
int length;
int capacity;
unsigned check;
char ptr[0];
} String; /* now String is a type */
Or explictly say struct String
:
void main(){
char *s;
struct String *new_string = malloc(sizeof(struct String) + 10 + 1);
}
As nobody seems to have mentioned this yet, let me explain what the code you used actually means.
What you used is a kind of shorthand notation that defines a struct and also creates a variable. It is equivalent to:
struct String {
int length;
int capacity;
unsigned check;
char ptr[0];
};
struct String String; //creates a global variable of type "struct String"
Later,
String *new_string
fails to compile because there is no type name by the name of "String" (only of "struct String". There is a global variable whose name is "String" but that doesn't make sense in this expression.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With