1

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?

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

Comments

1

Forget the *(ptr + idx) notation; it's used to confuse beginners, not in 'real code'. However, if you must use it, then:

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

But use:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.