0

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?

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.