gpt4 book ai didi

c - 在 C 中的结构中定义结构数组

转载 作者:太空宇宙 更新时间:2023-11-03 23:32:05 27 4
gpt4 key购买 nike

您好,我在定义结构中的结构数组时遇到了一些麻烦。这是我的想法,我需要一个名为 figure 的结构,它包含图形的名称、坐标计数和坐标 (x,y)。每个图形都可以有任意数量的坐标。我还需要能够为不断增加的坐标列表动态重新分配空间......请帮助我指明正确的方向。谢谢,

泰勒

typedef struct {
char fig_name[FIGURE_LEN + 1];
int coordcount;
/* here i need to declare an array of coord structures that
but i am not sure how to do this properly. I was originally
going to try something like as follows */
coords *pointer;
pointer = malloc(sizeof(coords));
pointer = coords figcoord[];
/* however i am quite certain that this would not work */
} figure;

typedef struct {
double x;
double y;
} coords;

最佳答案

向正确的方向踢球。尝试这样的事情。对于缺少对 malloc() 调用的错误检查,我深表歉意,但您会了解总体思路(我希望):

#include <stdlib.h>

#define FIGURE_LEN 128

typedef struct
{
double x;
double y;
} coords;

typedef struct
{
char fig_name[FIGURE_LEN + 1];
int coordcount;
coords *pointer;
} figure;


/* allocate a dynamic allocated figure */
figure* alloc_figure(char* name, int coordcount)
{
figure *fig = malloc(sizeof(figure));
fig->coordcount = coordcount;
fig->pointer = malloc(sizeof(coords) * coordcount);
strncpy(fig->fig_name, name, FIGURE_LEN);
fig->fig_name[FIGURE_LEN] = 0;
return fig;
}

/* release a dynamic allocated figure */
void free_figure(figure** ppfig)
{
if (!*ppfig)
return;

free((*ppfig)->pointer);
free(*ppfig);
*ppfig = NULL;
}

int main(int argc, char *argv[])
{
figure fig;
fig.coordcount = 10;
fig.pointer = malloc(10 * sizeof(coords));

/* access fid.pointer[0..9] here... */
fig.pointer[0].x = 1.0;
fig.pointer[0].y = 1.0;

/* don't forget to free it when done */
free(fig.pointer);

/* dynamic allocation function use */
figure *fig1 = alloc_figure("fig1", 10);
figure *fig2 = alloc_figure("fig2", 5);

fig1->pointer[9].x = 100.00;
fig2->pointer[0].y = fig1->pointer[9].x;

/* and use custom free function for releasing them */
free_figure(&fig1);
free_figure(&fig2);

return EXIT_SUCCESS;
}

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

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