Nathan
Nathan

Reputation: 483

Dynamic allocation of struct using C

I'm trying to allocate an array of struct. When I try to initialize a value and print the value within the function, everything works fine. When I go and print the same value in main, my program crashes.

void getHeader(FILE* fpFile, HEADER *pHead)
{
   //  Local Declaration
   int worker, salesWeek, i;
   PERSON *list;

   //  Statement
   fscanf(fpFile, "%d %d", &worker, &salesWeek);
   list = aloPerson(worker);
   HEADER header = {worker, salesWeek, list};
   pHead = &header;

   return;
}// getHeader


PERSON* aloPerson(int worker)
{
   //  Local Declaration
   PERSON *list;

   //  Statement
   list =(PERSON*)calloc(worker, sizeof(PERSON));
   if(list == NULL)
   {
      MEM_ERROR, exit(103);
   }

   return list;
}// aloPerson

This is my struct.

typedef struct
{
int worker;
int weeks;
PERSON *pAry;
}HEADER;

This is main:

int main ( void )
{
//  Local Declaration
FILE* fpFile;
char  nameIn[25];
char *endPro = "end";
HEADER *pHead;

//  Statement
printf("Please select file to to open.\nsales or sales_2: ");
scanf("%s", nameIn);
FLUSH;

do
{
    valiFile(nameIn);
    fpFile = openFile(nameIn);
    getHeader(fpFile, pHead);
    readFile(fpFile, pHead);

    repeat(nameIn);
}
while(strcmp(nameIn, endPro) != 0);


return 0;

Upvotes: 0

Views: 162

Answers (1)

Mahmoud Fayez
Mahmoud Fayez

Reputation: 3469

I think you need to change this line of code:

HEADER header = {worker, salesWeek, list};
pHead = &header;

to be:

HEADER header = {worker, salesWeek, list};
*pHead = header;

also make sure pHead is not null otherwise return error null param. If you want to go dynamic then allocate header variable using calloc then you can use your old code then.

make sure in your main function that this line

HEADER *pHead;

is changed to

HEADER *pHead = (HEADER*)calloc(1, sizeof(HEADER));

also do not forget to free it.

Upvotes: 5

Related Questions