Drew
Drew

Reputation: 2663

Char Pointers Overwritten

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?

Upvotes: 1

Views: 852

Answers (2)

Rami Jarrar
Rami Jarrar

Reputation: 4643

All pointers point to the same memory location, this can be done by changing the struct member label to

char label[100];

or by dynamically allocate memory like this,

if(i==0){
    set[count].label = (char *) malloc(sizeof(char)*(strlen(pch)+1));
    strcpy(set[count].label,pch);
}

Upvotes: 0

simonc
simonc

Reputation: 42175

You need to assign memory for each label instance. Either as an array

typedef struct Point {
    double x, y;
    char label[50];
} point;

strcpy(set[count].label, pch);

or by dynamically allocating memory for each label instance

set[count].label = malloc(strlen(pch)+1);
strcpy(label, pch);

(Make sure to later free(set[count].label) in the latter case)

Upvotes: 4

Related Questions