Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

* is illegal for a struct?

Tags:

c

pointers

struct

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

}
like image 871
user133466 Avatar asked Nov 26 '22 21:11

user133466


2 Answers

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);
}
like image 182
dave4420 Avatar answered Jan 11 '23 22:01

dave4420


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.

like image 29
Artelius Avatar answered Jan 11 '23 22:01

Artelius