I am creating a program that needs structs. I have written the entire program, but im having a problem loading from a txt file. My strut is
typedef struct{
int empid;
char *name;
}employee;
My read in method currently is
employee emparray[100];
int employees = 0;
FILE * employinfpt;
employinfpt = fopen("emps.txt", "r");
char line[100];
int tempint = 0;
char string[500];
while (fgets(line, sizeof(line), employinfpt)) {
//sscanf
sscanf(line, "%d %s", &tempint, string);
emparray[employees].empid = tempint;
emparray[employees].name = string;
//increase employees
employees++;
}
fclose(employinfpt);
My problem is when I try to access the struct array, they all have the same value as the last string. I'm a bit of a noob and i have no idea where i am going wrong. anybody have any advice at all?
They all point to the same array.
Try
emparray[employees].name = strdup(string);
then, when it works, read about dynamic memory allocation to understand what you're doing here.