David Refaeli David Refaeli - 1 year ago 71
C Question

Accessing an array element inside a struct (which is part of an array of structs) (in C)

I want to create an array of structs, though the no. of structs in the array is read from a file / input from user.

I declare a struct:

struct student{
char name[16];
int *available;
int sum;

typedef struct student ST;

I allocate memory for the array of structs (after getting the input of size):

ptr = (ST*)calloc(lines, sizeof(ST));

I also allocate space for each array in each struct (using a loop):

ptr->available = (int*)calloc(lines, sizeof(int));

NOW - I want to put values in these arrays. How do I reach each element?

I tried:

*((ptr+i)->(available+j)) = 1;

But the compiler tells me:
error: expected identifier before ‘(’

(i and j are indexes I use, i for the i'th struct, and j for the j'th element of the array).

What am I doing wrong?

Answer Source

Consider using array index notation for readability:

ptr[i].available[j] = 1;

(The equivalent syntax using explicit pointer arithmetic is the considerably more obfuscated *((ptr + i)->available + j) = 1;)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download