Ok here's what I've got now, I have made some minor revisions to the structure and names of stuff so it might be a little hard to follow from the previous example, but nothing too major.
The main.c file
The student.h header file (note I made a couple of changes to the structures)Code:#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "student.h"
#define BUFSIZE 256
int main()
{
record *array = 0;
record std;
int number_of_elements = 0;
int array_size = 0;
char line[BUFSIZE];
char first[21];
char last[21];
int score;
/*get the user input line while not EOF*/
while (fgets(line, BUFSIZE, stdin) != 0)
{
sscanf(line, "%s%s%d", last, first, &score);
strcpy(std.name.lastname, last);
strcpy(std.name.firstname, first);
std.score = score;
add(&array, &std, &number_of_elements, &array_size);
}
free(array);
return 0;
}
and finally the student.c file which includes the dynamic arrayCode:#include <stdlib.h>
#ifndef STUDENT_C
#define STUDENT_C
#define NAMESIZE 21
typedef struct name
{
char lastname[NAMESIZE];
char firstname[NAMESIZE];
} name;
typedef struct record
{
name name;
int score;
} record;
void add(record**, record*, int*, int*);
#endif
To recap, it compiles and runs fine, the dynamic array works fine for the first string I enter, but it segfaults when I enter the second one :S this random behavior kind of leads me to believe it has to do with something not being initalized or something along those lines.Code:#include <stdlib.h>
#include <stdio.h>
#include "student.h"
void add(record **array, record *item, int *number_of_elements, int *array_size)
{
if (*number_of_elements == *array_size) /*resize array*/
{
if (*array_size == 0)
{
*array_size = 1;
}
else
{
*array_size = *array_size * 2;
}
*array = (record*)realloc(*array, ((*array_size) * sizeof(record)));
if (*array == 0)
{
printf("no space for memory");
exit(1);
}
}
*array[*number_of_elements] = *item;
(*number_of_elements)++;
}
I'm thinking maybe it is something to do with the main, but whatever it is I've been fooling around with it for hours and can't seem to figure it out.
TIA

