Click here to Skip to main content
15,892,537 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
How do I access a specific array element if I have a pointer to a struct which has a pointer to an array of structs?


struct node {
int number;
};

struct queue {
struct node *array;
};

int main() {
struct queue *queues;
struct node *t;
queues = (struct red*)malloc(sizeof(struct queue));
queues->array = (struct node*)malloc(10 * sizeof(struct node));
queues->array->number = 5;
queues->(array + 1)->number = 6
}

What I have tried:

queues->array->number can access the first element,but how do i access other elements?

queues->(array + i)->number doesnt work and
queues->array[i]->number doesnt work
Posted
Updated 14-Apr-19 3:40am

You need to use the dot referencer since array[i] is a proper reference, rather than a pointer (I know it's confusing but that is the rule in C). So you should code it as follows:
C++
int i = 3; // or any other offset
queues->array[i].number = 6;
 
Share this answer
 
First off, get it to compile! "red" is not declared:
queues = (struct red*)malloc(sizeof(struct queue));
I assume you meant:
queues = (struct queue*)malloc(sizeof(struct queue));

Then just use it as an array:
queues->array[1].number = 6;
struct node *n = queues->array;
for (int i = 0; i < 10; i++)
    {
    printf("%u\n", n[i]);
    }
Will give you:
5
6
0
0
0
0
0
0
0
0
(Though the zeros may be replaced with random data, depending on your compiler)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900