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);
}
You forgot the
typedef
:use this code:
you can also consider typedef
will let you use your snippet:
Try:
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... :)
Either use a typedef:
Or explictly say
struct String
:Edit: I now see that the original question was tagged
C
and notC++
and someone erroneously tagged itC++
(reverted the tagging).One solution, as others mentioned, is to add a
typedef
before thestruct
declaration however since this isC++
(according to the question's tag) and notC
a more idiomatic and shorter way would be to just drop the trailing "String"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 calledString
you introduced a variable calledString
which hid the type.As artelius wrote earlier, your struct definition is likely not what you want. The easiest fix would be:
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.