【问题标题】:How can a structure have dynamically allocated members in C?结构如何在 C 中动态分配成员?
【发布时间】:2020-05-26 23:47:35
【问题描述】:

我尝试使用以下代码将对象动态分配为结构的成员:

#include <stdlib.h>
#define width 4

struct foo{
     int* p1 = malloc(sizeof(*p1) * width);   
};

但是编译器,无论是 clang 还是 gcc,都会抛出错误:

error: expected ':', ',', ';', '}' or '__attribute__' before '=' token

当我尝试编译代码时;这是链接:https://godbolt.org/z/-Sy6CK

我的问题:

  • 如何在 C 中创建具有动态分配成员的结构?

【问题讨论】:

  • 你不能在结构中内联初始化。您必须在函数中进行初始化。
  • 首先,你将它定义为一个不指定任何值的指针,比如int *p1;,然后在那里,在其他一些函数中,你可以分配内存并分配指针值以指向分配的内存空间,如p1 = malloc(n * sizeof(someVarOrStruct));
  • 顺便说一句,如果width 是编译时常量(如问题所示),那么为什么要使用指针和动态分配开始呢?为什么不是数组,比如int p1[width];
  • @Someprogrammerdude 你说的没错,但我想让这个例子尽可能简单,以便“直奔主题”,而不会过多地分散其他事情的注意力。选择动态分配的主要原因是稍后根据需要调整成员的大小。
  • @Someprogrammerdude 指导我的是 C++ 的处理。在 C++ 中,可以使用 new:struct foo{ int* p1 = new int; }; 立即为 structclass 的成员分配内存但是当然,C 不是 C++,反之亦然。

标签: c data-structures struct dynamic malloc


【解决方案1】:

或者这个:

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

【讨论】:

  • 我对这种技术非常着迷。如果foo 使用花括号方法有更多成员,我可以初始化bar 的更多成员吗?比如:struct foo bar = {.p1 = malloc(sizeof(*bar.p1) * width)} {.c = 24}; 如果foo 有额外的成员int c;
【解决方案2】:

你想要这个:

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

【讨论】:

    猜你喜欢
    • 2017-06-11
    • 1970-01-01
    • 2021-08-25
    • 1970-01-01
    • 1970-01-01
    • 2016-01-18
    • 2022-11-07
    • 2021-01-25
    • 2017-02-04
    相关资源
    最近更新 更多