So in my program there’s a struct:
typedef struct Point {
double x, y;
char *label;
} point;
And then I read some information from a file and assign various labels to various point structs within an array. The problem is that although the x, y values are assigned properly, the label is the same for each struct in memory.
point set[3];
FILE *file = fopen(argv[1], "r");
int count = 0;
char *pch;
char line[128];
if(file != NULL){
while(fgets (line, sizeof line, file) != NULL){
pch = strtok(line, " ");
int i = 0;
while(pch != NULL){
if(i==0){set[count].label = pch;}
if(i==1){set[count].x = atof(pch);}
if(i==2){set[count].y = atof(pch);}
pch = strtok(NULL, " ");
i++;
}
count++;
}
fclose(file);
}
//these values should not be the same, though they are
printf("%s\n", set[0].label);
printf("%s\n", set[1].label);
Is there some sort of workaround that would allow my struct to remain the same and yet assign values properly?
You need to assign memory for each label
instance. Either as an arrayor by dynamically allocating memory for each
labelinstance(Make sure to later
free(set[count].label)in the latter case)