-

2011年8月3日星期三

I'm having trouble reading a txt file into an array of structs using dynamic memory allocation. Help please?

-I'm trying to do a simple program that will read data from a text file into an array of structures using dynamic memory allocation and then printing it. Here is the text file exactly as it was given to me:



Fred Flintstone 38 Male

Barney Rubble 36 Male

Wilma Flintstone 37 Female

Betty Rubble 36 Female

Pebbles Flintstone 4 Female

Bam-Bam Rubble 3 Male

Dino Flintstone 2 Male



IMPORTANT: There are 3 tabs (not spaces) before the numbers and 2 tabs after the numbers. I'm getting no errors or warnings, but my output box crashes. I'm sure my while loop is where the problem is. Any tips would be helpful. Thank you. Here is my code:



#include <stdio.h>

#include <stdlib.h>

#include <string.h>



int main(void)

{

typedef struct

{

char* name;

int* age;

char* gender;

}CHARACTER;



CHARACTER* pChar;

int charIndex;

char temp[61];



FILE* pData;



if ((pData = fopen("lab4data.txt", "r"))==NULL)

{

printf("Error opening file.\n");

return 100;

}



pChar = (CHARACTER*) calloc(7, sizeof(CHARACTER));



charIndex = 0;

while (charIndex<7)

{

fgets(temp, 20, pData);

pChar[charIndex].name = (char*)calloc(strlen(pChar[charIndex].na鈥?+ 1, sizeof(char));

strcpy(pChar[charIndex].name, temp);



pChar[charIndex].age = (int*)malloc(sizeof(int));

fscanf(pData, "%d", pChar[charIndex].age);



fgets(temp, 15, pData);

pChar[charIndex].gender = (char*)calloc(strlen(pChar[charIndex].ge鈥?+ 1, sizeof(char));

strcpy(pChar[charIndex].gender, temp);



charIndex++;

}



for (charIndex=0; charIndex<7; charIndex++)

{

printf("%s %d %s", *pChar[charIndex].name, *pChar[charIndex].age, *pChar[charIndex].gender);

}



if (fclose(pData) == EOF )

{

printf("Error closing lab3data.txt\n");

return 200;

}



return 0;

}This:

pChar[charIndex].name = (char*)calloc(strlen(pChar[charIndex].na鈥?+ 1, sizeof(char));

I assume is:

pChar[charIndex].name = (char*)calloc( strlen(pChar[charIndex].name) + 1, sizeof(char));



But what is in pChar[charIndex].name when you call that? It's all 0's, right? You haven't put anything into it yet. calloc set it to 0's. So...it's a NULL pointer, right?



You need to compute the size you need to allocate from the data you read in.

没有评论:

发表评论