Reputation: 41
So I think I've seen before you can allocate memory in C inside a struct so you don't need to do it in when you create a variable. basically
typedef struct Data{
//Any Arbitrary data
char *name;
} Data;
int main(void){
Data* x = (Data*) malloc(sizeof(Data));
}
Is there some way I can do it from inside the struct like:
typedef struct Data{
(Data*) malloc(sizeof(Data));//<---Something to allocate memory?
//Any Arbitrary data
char *name;
} Data;
int main(void){
Data* x;
Data* y;
Data* z;
}
Upvotes: 2
Views: 64
Reputation: 26194
You have just discovered the need for classes that wrap resources and the concept of a constructor!
There is no way to do it in standard C. If you want such features, your best bet is to try C++ or perhaps use some C extension. GCC has the cleanup attribute for example.
In non-idiomatic C++ it would look like:
struct Data {
char *name;
Data() {
name = (char*) malloc(sizeof(char)*100);
// it will allocate 100 bytes to the string everytime.
}
// other things to avoid leaking memory, copying the class, etc.
};
int main() {
Data x; // allocates
Data y; // also allocates
}
This example shows how you would allocate for name
in C++, but you can also allocate for Data
itself. C++ has utilities like std::unique_ptr<Data>
to do it for you.
Upvotes: 2