[英]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.所以我想我以前见过你可以在结构内部的 C 中分配 memory ,因此在创建变量时不需要这样做。 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.在标准 C 中没有办法做到这一点。 If you want such features, your best bet is to try C++ or perhaps use some C extension.如果您想要这些功能,最好的办法是尝试 C++ 或者使用一些 C 扩展。 GCC has the cleanup attribute for example.例如 GCC 具有清理属性。
In non-idiomatic C++ it would look like:在非惯用的 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
}
This example shows how you would allocate for name
in C++, but you can also allocate for Data
itself.此示例显示了如何为 C++ 中的name
分配,但您也可以为Data
本身分配。 C++ has utilities like std::unique_ptr<Data>
to do it for you. C++ 有像std::unique_ptr<Data>
这样的实用程序来为你做这件事。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.