* 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条回答
女痞
2楼-- · 2019-06-24 10:26

You forgot the typedef:

typedef struct String {
    int length;
    int capacity;
    unsigned check;
    char ptr[0];
} String;
/* String is now a type, not an object */

void main(){

    char *s;
    String *new_string = malloc(sizeof(String) + 10 + 1);
}
查看更多
家丑人穷心不美
3楼-- · 2019-06-24 10:27

use this code:

struct String* new_string = malloc(sizeof(String)+10+1);

you can also consider typedef

typedef struct String sString;

will let you use your snippet:

sString* mystring
查看更多
We Are One
4楼-- · 2019-06-24 10:29

Try:

 typedef struct String_t {
        int length;
        int capacity;
        unsigned check;
        char ptr[0];
    } String;

Yours doesn't quite declare a type like that. More specifically, it hides your type by introducing a variable of the same name. And that gets the compiler confused... :)

查看更多
Deceive 欺骗
5楼-- · 2019-06-24 10:30

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);
}
查看更多
闹够了就滚
6楼-- · 2019-06-24 10:33

Edit: I now see that the original question was tagged C and not C++ and someone erroneously tagged it C++ (reverted the tagging).


One solution, as others mentioned, is to add a typedef before the struct declaration however since this is C++ (according to the question's tag) and not C a more idiomatic and shorter way would be to just drop the trailing "String"

struct String {
    int length;
    int capacity;
    unsigned check;
    char ptr[0];
};

This is enough to introduce a type called String the reason your original code didn't work was that in addition to introducing a type called String you introduced a variable called String which hid the type.

查看更多
\"骚年 ilove
7楼-- · 2019-06-24 10:36

As artelius wrote earlier, your struct definition is likely not what you want. The easiest fix would be:

#include <stdlib.h>

struct String {
    int length;
    int capacity;
    unsigned check;
    char ptr[0];
};

int main(){
    char *s;
    String *new_string = (String*)malloc(sizeof(String) + 10 + 1);
    return 0;
}

This actually compiles too when I tested with both gcc and g++. If you are really doing C++ as your tags imply, you should rather include cstdlib instead of stdlib.h or do it properly(tm) and turn your string into a class and use new.

查看更多
登录 后发表回答