简体   繁体   中英

Why my C code is giving me “segmentation fault” error when I try to read dynamically allocated array contents?

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,(ie 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;
}

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM