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);
}
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:
Later,
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.
Yes, it is true. Binary
*
operator (multiplication) is only applicable to arithmetic types. In your example you declared a variableStruct
of typestruct Struct
and then tried to multiply it by something. This just doesn't make any sense. You can't multiply struct objects. This is what the compiler is telling you.Additionally: 1. That's
int main
, notvoid main
. 2. C language doesn't support array declarations with size 0. You might want to change the array declaration inside your struct type.