簡體   English   中英

如何從結構內部分配 C 中的 memory?

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

所以我想我以前見過你可以在結構內部的 C 中分配 memory ,因此在創建變量時不需要這樣做。 基本上

typedef struct Data{
    //Any Arbitrary data
    char *name;

} Data;

int main(void){
    Data* x = (Data*) malloc(sizeof(Data));
}

有什么方法可以從結構內部做到這一點,例如:

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

您剛剛發現需要包裝資源的類和構造函數的概念!

在標准 C 中沒有辦法做到這一點。 如果您想要這些功能,最好的辦法是嘗試 C++ 或者使用一些 C 擴展。 例如 GCC 具有清理屬性。

在非慣用的 C++ 中,它看起來像:

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
}

此示例顯示了如何為 C++ 中的name分配,但您也可以為Data本身分配。 C++ 有像std::unique_ptr<Data>這樣的實用程序來為你做這件事。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM