在C中,一个结构如何能够动态分配成员?
我已尝试使用以下代码将对象动态分配为结构的成员:在C中,一个结构如何能够动态分配成员?,c,data-structures,struct,dynamic,malloc,C,Data Structures,Struct,Dynamic,Malloc,我已尝试使用以下代码将对象动态分配为结构的成员: #include <stdlib.h> #define width 4 struct foo{ int* p1 = malloc(sizeof(*p1) * width); }; 当我试图编译代码时;以下是链接: 我的问题: 如何创建在C中动态分配成员的结构 您想要这个: #include <stdlib.h> #define width 4 // declaration, you can't do
#include <stdlib.h>
#define width 4
struct foo{
int* p1 = malloc(sizeof(*p1) * width);
};
当我试图编译代码时;以下是链接:
我的问题:
- 如何创建在C中动态分配成员的结构
#include <stdlib.h>
#define width 4
// declaration, you can't do initialisation here
struct foo{
int* p1;
};
int main()
{
struct foo bar;
bar.p1 = malloc(sizeof(*bar.p1) * width);
}
#包括
#定义宽度4
//声明,您不能在这里进行初始化
结构foo{
int*p1;
};
int main()
{
结构富吧;
bar.p1=malloc(sizeof(*bar.p1)*宽度);
}
或者:
struct foo{
int* p1;
};
int main()
{
struct foo bar = {.p1 = malloc(sizeof(*bar.p1) * width)};
}
或
不能在结构中内联初始化。您必须在函数中进行初始化。首先,您将其定义为一个指针,不分配任何值,如
int*p1代码>,然后在下面的其他函数中,您可以分配内存并分配指针值以指向分配的内存空间,如p1=malloc(n*sizeof(someVarOrStruct))代码>。顺便说一句,如果宽度
是一个编译时常量(如问题所示),那么为什么要从使用指针和动态分配开始呢?为什么不是数组,如intp1[width]
?@Someprogrammerdude你说的没错,但我只是想让这个例子尽可能简单,“直截了当地”去做,而不需要太多其他事情的干扰。选择动态分配的主要原因是,如果需要,稍后调整成员的大小。@一些指导我的是从C++中处理的。在C++中,可以通过使用<代码> new < /C> >:<代码> >结构> fo{int *p1= new int;},立即分配一个<代码>结构> <代码>或<代码>类< /代码>的内存。当然,C当然不是C++,反之亦然。我对这项技术非常着迷。如果foo
使用花括号方法会有更多的成员,我可以初始化bar
的更多成员吗?比如:structfoobar={.p1=malloc(sizeof(*bar.p1)*宽度)}{.c=24}代码>如果foo
有额外的成员intc代码>?
struct foo{
int* p1;
};
int main()
{
struct foo bar = {.p1 = malloc(sizeof(*bar.p1) * width)};
}
int main()
{
struct {
int* p1;
} bar = {.p1 = malloc(sizeof(*bar.p1) * width)};
}