1

I have run into a problem or maybe I am just doing something wrong since I am new to C and structs. I want to take a text file such as this:

3
Trev,CS,3.5
Joe,ART,2.5
Bob,ESC,1.0

and read in the first line as the number of students then from there out gather student info and put them in a struct called StudentData:

typedef struct StudentData{
 
 char* name;
 char* major;
 double gpa;
 
} Student;

Where I run into a problem is after I seemingly assign the data to an individual struct, the struct data becomes mixed up. I have commented out exactly what is going on (or at least what I believe is). Hopefully it isn't painful to read.

main(){
 int size, i;
 char* line = malloc(100);
 scanf("%d\n", &size);//get size
 char* tok;
 char* temp;
 Student* array[size]; //initialize array of Student pointers
 for(i = 0; i<size;i++){
 array[i] = malloc(sizeof(Student));//allocate memory to Student pointed to by array[i]
 array[i]->name = malloc(50); //allocate memory for Student's name
 array[i]->major = malloc(30);//allocate memory for Student's major
 }
 
 for(i = 0; i<size;i++){
 scanf("%s\n", line);//grab student info and put it in a string
 tok = strtok(line, ","); //tokenize string, taking name first
 array[i]->name = tok;//assign name to Student's name attribute
// printf("%s\n",array[i]->name);//prints correct value
 line = strtok(NULL, ",");//tokenize
 array[i]->major = line;//assign major to Student's major attribute
// printf("%s\n",array[i]->major);//prints correct value
 temp = strtok(NULL, ",");//tokenize
 array[i]->gpa = atof(temp);//assign gpa to Student's gpa attribute
// printf("%.2f\n\n",array[i]->gpa); //prints correct value
 }
 
 for(i=0;i<size;i++){ //this loop is where the data becomes jumbled
 printf("%s\n",array[i]->name);
 printf("%s\n",array[i]->major);
 printf("%.2f\n\n",array[i]->gpa);
 }
}

The output looks like this:

Trev
Joe
3.50
Joe
Bob
2.50
Bob
ESC
1.00

I can't really understand what is going on in the memory between assigning values and printing them.

halfer
20.2k19 gold badges110 silver badges207 bronze badges
asked Sep 25, 2011 at 15:04

1 Answer 1

3

You can't use regular assignment with char * like that. You will need to use strcpy. For example:

strcpy(array[i]->name,tok);

Otherwise you are making all the array[i]->name point to the same string.

answered Sep 25, 2011 at 15:08
Sign up to request clarification or add additional context in comments.

1 Comment

how would i handle the string to double?

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.