在C语言中,将结构体赋值给结构体内部的另一个结构体



我想将一个结构体赋值给一个结构体中的字段,该字段是指向该结构体的指针。我将在下面展示我所说的内容:

typedef struct {
    char *name;
} geometry;
typedef struct sceneGR_tag {
    geometry *g;
    struct sceneGR_tag *next;
} sceneGR;
typedef struct {
    geometry *g;
    int nshapes;
    sceneGR *root;  
} scene;

可以看到,sceneGR有一个几何*g(一个几何数组)。前提是我已经初始化了结构体'scene'及其几何结构,我想将其几何结构复制到结构体'sceneGR'中,因此在sceneGR->g中。

如何在我的for中做到这一点?:

scene *scn; //already initialized with nshapes=6, and so with 6 geometries until g[5];
for(k = 0; k < scn->nshapes; k++) {
    //what can i do here?
}

为什么需要循环?你只需要做:

scn->root->geometry = scn->geometry;

如果不是你想要的,请告诉我。

编辑

要将scn->g的每个几何值复制到每个sceneGR->g中。但这很奇怪,除非你的struct scene中有geometry** g。但是,您可以使用自己的代码:

scene *scn;
sceneGR *s_list = scn->root;
for(k = 0; k < scn->nshapes; k++) {
    s_list->g = &(scn->g[k]);
    s_list = s_list->next;
}

但是在您的struct scene中有geometry** g,您可以:

scene *scn;
sceneGR *s_list = scn->root;
for(k = 0; k < scn->nshapes; k++) {
    s_list->g = scn->g[k];
    s_list = s_list->next;
}

如果geometry的定义使得按位复制有意义,则:

SceneGR *gr = malloc(sizeof *gr);
size_t num_bytes_to_copy = scn->nshapes * sizeof scn->g[0];
gr->next = NULL;
gr->g = malloc( num_bytes_to_copy );
memcpy(gr->g, scn->g, num_bytes_to_copy );

如果没有,则必须为每个geometry对象循环调用copy-函数。

也不清楚SceneGR应该如何知道它的数组中有多少项。

当你销毁SceneGR的时候不要忘记free(gr->g)

最新更新