正しい方向に蹴ります。このようなことを試してください。呼び出しのエラーチェックが不足していることをお詫びし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;
}