Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
586 views
in Technique[技术] by (71.8m points)

c - malloc an array of struct pointers

I have the following struct:

typedef struct _chess {
   int **array;
   int size;
   struct _chess *parent;
} chess;

and I have:

typedef struct _chess *Chess;

Now, I want to create an array of dynamic length to store pointers to the chess struct so I do the following:

Chess array [] = malloc(size * sizeof(Chess));

This gives me an error: invalid initializer.

And if I drop the [] and do this:

Chess array = malloc(size * sizeof(Chess));

it compiles without error but when I try to set an element of this array to NULL by doing:

array[i]=NULL;

I get an error: incompatible types when assigning to type ‘struct _chess’ from type ‘void *’

Any idea what am I doing wrong? Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

array is a slightly misleading name. For a dynamically allocated array of pointers, malloc will return a pointer to a block of memory. You need to use Chess* and not Chess[] to hold the pointer to your array.

Chess *array = malloc(size * sizeof(Chess));
array[i] = NULL;

and perhaps later:

/* create new struct chess */
array[i] = malloc(sizeof(struct chess));

/* set up its members */
array[i]->size = 0;
/* etc. */

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...