动态分配的C结构? [英] Dynamically allocate C struct?

查看:117
本文介绍了动态分配的C结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要动态分配一个C结构:

  typedef结构{
    短*抵消;
    字符*值;
} SWC;

这两个偏移和价值应该是数组,但是它们的大小是未知的,直到运行时。

我如何动态地为我的结构和结构的数组分配内存?


解决方案

  SWC * A =(SWC *)malloc的(的sizeof(SWC));
A->偏移量=(短*)malloc的(的sizeof(短)* N);
A->值=(字符*)malloc的(的sizeof(char)的* N);

其中,n =每个阵列中的项目和一个数是新分配的数据结构的地址。不要忘了之前免费给free()偏移量和值()ING一个。

I want to dynamically allocate a C struct:

typedef struct {
    short *offset;
    char *values;
} swc;

Both 'offset' and 'values' are supposed to be arrays, but their size is unknown until runtime.

How can I dynamically allocate memory for my struct and the struct's arrays?

解决方案

swc *a = (swc*)malloc(sizeof(swc));
a->offset = (short*)malloc(sizeof(short)*n);
a->values = (char*)malloc(sizeof(char)*n);

Where n = the number of items in each array and a is the address of the newly allocated data structure. Don't forget to free() offsets and values before free()'ing a.

这篇关于动态分配的C结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆