Reputation: 9
As the question explains, I'm creating a dynamically allocated array of structures(as i called, struct Desk*) in my C code. In the main function, I am giving int id numbers in the "int deskId" fields of them .When I try to read their id's inside the main function, code works as expected. On the other hand, if I try to read their id contents outside the main (as in the code below) it gives segmentation fault(core dumped) error. I am giving the problematic code below. As you see, I paid attention to give the address of the array parameter,(i.e. pointer to the actual array) so that i can read the actual content of the array, no the local copy. Thanks in advance.
#include <stdio.h>
#include <stdlib.h>
#include "queue.h"
struct Desk {
int deskId;
Queue deskQueue;
};
struct TaxPayer {
int id; // tax payer ID
float duration; // payment duration
};
//function to display the ids of the desks
int display (int desks, struct Desk** argsptr) {
int i=0;
while(i < desks) {
printf ("My argument's id is %d\n",argsptr[i]->deskId );
i++;
}
return 0;
}
int main (int argc, char *argv[]) {
int option_index = 0;
int p_num = 20;
int desk_num = 4;
int max_q_size = 3;
//initialize array of desks
struct Desk* desk_array = malloc(desk_num * sizeof(struct Desk));
for (int i= 0; i < desk_num; i++) {
queueInit(&desk_array[i].deskQueue, sizeof(struct TaxPayer));
desk_array[i].deskId = i;
}
display(desk_num, &desk_array);
free(desk_array);
return 0;
}
Upvotes: 0
Views: 140
Reputation: 222302
argsptr[i]->deskId
accesses an array of struct Desk *
, but there is only one. You need (*argsptr)[i].deskId
.
Alternatively, pass desk_array
instead of &desk_array
, change the parameter type to struct Desk *
, and use argsptr[i].deskId
.
Upvotes: 1
Reputation: 276
You're passing the address of the desk_array
pointer to display()
rather than the pointer itself. display()
is then reading the pointer, then the area of memory after the pointer, etc. What you want to do is pass the pointer desk_array
, and then use .
rather than ->
inside the function because the [i]
dereferences desk_array
.
int display (int desks, struct Desk* argsptr) {
int i=0;
while(i < desks) {
printf ("My argument's id is %d\n",argsptr[i].deskId );
i++;
}
return 0;
}
...
display(desk_num, desk_array);
Upvotes: 2