简体   繁体   中英

How do I allocate memory in C from inside the struct?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM