* is illegal for a struct?

2019-06-24 09:51发布

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);

}

8条回答
SAY GOODBYE
2楼-- · 2019-06-24 10:37

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.

查看更多
再贱就再见
3楼-- · 2019-06-24 10:40

Yes, it is true. Binary * operator (multiplication) is only applicable to arithmetic types. In your example you declared a variable Struct of type struct 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, not void main. 2. C language doesn't support array declarations with size 0. You might want to change the array declaration inside your struct type.

查看更多
登录 后发表回答