c - strtok overwrites my variables -
i'm trying use strtok () store info struct. code looks this
char *temptype = null, name[100], filestring[100]; int *tempitems = null, *tempcost = null; file *infile = null; itemtype myvector; infile = fopen ("grocery_list.txt", "r"); while (!feof (infile)) { fscanf (infile, "%s", &filestring); temptype = strtok (filestring, ":"); tempcost = (int *) strtok (null, ":"); tempitems = (int *) strtok (null,":"); myvector.type[num_items] = temptype; myvector.cost[num_items] = tempcost; myvector.items[num_items] = tempitems; num_items++; }
everytime run it, values in myvector.type becomes "cherries" , i'm not sure why. infile: apples:5:1 milk:3:2 bread:3:1 candy:10:1 cheese:5:6 oranges:4:2 cherries:3:2
the function strtok returns pointer , pointer gets overwritten each execution of while loop. in end array entries point same memory address. need copy string strtok returns.
Comments
Post a Comment