gpt4 book ai didi

c - C 中结构体的 Malloc 数组

转载 作者:行者123 更新时间:2023-11-30 16:43:35 37 4
gpt4 key购买 nike

这就是我所做的:我计算文件夹内文件的数量,从结构数组内的该文件获取数据。我想 malloc 这个结构体数组,因为在编写程序之前我不知道文件的确切数量。

这是我的代码:

struct get_data{
int sequence;
int mask_ID;
char *name;
float intensity;
float angle_correction;
double points[10000];
float X_interval;
};

struct get_data all_data[number_of_file];

考虑一下我在程序中的某个位置之前获得了 number_of_file 。我想知道如何 malloc struct all_data。我搜索但在某个时候迷路了。任何帮助都会受到欢迎。谢谢。

梅尔。

最佳答案

我建议您为结构内的名称变量指定固定长度,否则您必须为每个结构malloc该长度。该声明可能如下所示:

struct get_data
{
int sequence;
int mask_ID;
char name[256];
float intensity;
float angle_correction;
double points[10000];
float X_interval;
};

然后,您可以使用以下代码malloc结构体数组:

struct get_data *all_data;

all_data = malloc(number_of_files * sizeof(struct get_data));
if (all_data == NULL)
{
printf("Malloc failed!\n);
return -1;
}

/* now you can access each file structure using a for instruction */
int i;
for (i = 0; i < number_of_files; i++)
{
all_data[i].sequence = ...;
/* etc. */
}

关于c - C 中结构体的 Malloc 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45147695/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com