开发者

How can I deal with an array of structs?

I have this struct:

#define sbuffer 128
#define xbuffer 1024

typedef struct{
    char name[sbuffer];
    char att[sbuffer];
    char type[sbuffer];
    int noOfVal;
    int ints[xbuffer];
    double doubles[xbuffer];
    char *strings[xbuffer开发者_如何转开发];
} variable;

I need to create an array from this struct, I did this

variable *vars[512]; //is it right

If I want to put a string that I had in s into the name, I did this:

char *s = "What Ever";
strcpy(vars[0]->name,s);

but this doesn't work for me, can anyone help?


Get rid of the * in this line:

variable *vars[512]; //is it right

And use dot syntax to access the struct member in strcpy:

char *s = "What Ever";
strcpy(vars[0].name,s); 


You've allocated an array of pointers to your struct, but never created instances (allocated memory) of them. You could either make it an array of the structures (without the pointers) so you don't have to worry about memory management.

char *s = "What Ever";
variable vars[512]; /* an array of your structure */
strcpy(vars[0].name,s); /* <- use dot operator here since they are no longer pointers */

Or at least allocate memory for the structure before using it (and initializing all other pointers to NULL).

char *s = "What Ever";
variable *vars[512]; /* an array of pointers to your structure */
vars[0] = (variable *)malloc(sizeof(variable)); /* dynamically allocate the memory */
strcpy(vars[0]->name,s); /* <- used arrow operator since they are pointers */


I think you need to use

variable vars[512];

instead of

variable *vars[512]


variable *vars[512] = {NULL};

int i = 0;

//i may get a value in some way

if (NULL == vars[i]){
    vars[i] = (variable *)malloc(sizeof(struct variable));
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜