dav*_*420 21
要么使用typedef:
typedef struct String {
int length;
int capacity;
unsigned check;
char ptr[0];
} String; /* now String is a type */
Run Code Online (Sandbox Code Playgroud)
或者明确地说struct String
:
void main(){
char *s;
struct String *new_string = malloc(sizeof(struct String) + 10 + 1);
}
Run Code Online (Sandbox Code Playgroud)
Art*_*ius 18
由于似乎没有人提到这一点,让我解释一下你使用的代码究竟意味着什么.
您使用的是一种简写符号,用于定义结构并创建变量.它相当于:
struct String {
int length;
int capacity;
unsigned check;
char ptr[0];
};
struct String String; //creates a global variable of type "struct String"
Run Code Online (Sandbox Code Playgroud)
后来,
String *new_string
Run Code Online (Sandbox Code Playgroud)
无法编译,因为没有名称为"String"的类型名称(仅限于"struct String".有一个全局变量,其名称为"String"但在此表达式中没有意义.
你忘记了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);
}
Run Code Online (Sandbox Code Playgroud)