开发者

c struct relationships

//CHILD
typedef struct Child{
    int id;
开发者_高级运维}Child;
Child* newChild(){
    Child *aChild = malloc(sizeof(Child));
    aChild->id = 0;
    return aChild;
}

//PARENT
typedef struct Parent{
    int id;
    Child **children;
}Parent;

Parent* newParent(){
    Parent *aParent = malloc(sizeof(Parent));
    aParent->id = 0;
    aParent->children = malloc(sizeof(Child*) * 5);//ARRAY OF 5 CHILDREN?
    for(i=0; i<5; i++){
        aParent->children[i] = newChild();
    }
    return aParent;
}

Is the newParent() function a correct way to create a struct with an array children? My main concern is the line:

aParent->children = malloc(sizeof(Child*) * 5);


You should check if malloc actually succeeded, but other than that, the code is OK.


As Let_Me_Be says, there is nothing wrong in principle with the code. However, I'd like to point out if I can that you are probably wanting to do this:

Parent *p = newParent();

But what isn't apparent is that a lot of memory has just been allocated. If you don't keep track of it, or forget to free it, you have a problem. Also, you don't know how many children a Parent has should you wish to resize it. I might suggest:

typedef struct Parent{
    int id;
    int numchildren;
    Child **children;
}Parent;

and I might propose functions like:

int parent_array_Initialise(Parent *p, int num_children)
{
    p = malloc(sizeof(Parent));
    ...
}

int parent_array_children_resize(Parent *p, int new_children_size);

int parent_array_Free(Parent *p);

You then call the functions. The idea would be to return the result of the malloc (size of array if success, 0 if failure) in each case so you can test the malloc result.

Just my personal taste. Whatever you do, pass the results through valgrind or similar just to make sure you're not leaking memory.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜