Rami Jarrar
Rami Jarrar

Reputation: 4643

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?

Upvotes: 0

Views: 1045

Answers (4)

Jeff Mercado
Jeff Mercado

Reputation: 134871

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 */

Upvotes: 1

Jacob Relkin
Jacob Relkin

Reputation: 163248

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); 

Upvotes: 5

William X
William X

Reputation: 7011

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));
}

Upvotes: 0

rldrenth
rldrenth

Reputation: 35

I think you need to use

variable vars[512];

instead of

variable *vars[512]

Upvotes: 0

Related Questions