C struct string error -
here chunks of code give view of problem
typedef struct { int count; char *item; int price; char *buyer; date *date; }transaction; transaction *open(file *src, char* path) { char buffer[100], *token; int count = 0; transaction *tlist = (transaction*)malloc(sizeof(transaction)); tlist = alloc(tlist, count); src = fopen(path, "r"); if (src != null) { printf("\nsoubor nacten.\n"); } else { printf("\nchyba cteni souboru.\n"); return null; } while (fgets(buffer, sizeof(buffer), src)) { tlist = alloc(tlist, count+1); token = strtok(buffer, "\t"); //zahodit jméno obchodníka tlist[count].count = strtok(null, "x"); tlist[count].item = strtok(null, "\t"); tlist[count].item++; tlist[count].item[strlen(tlist[count].item)] = '\0'; tlist[count].price = atoi(strtok(null, "\t ")); token = strtok(null, "\t"); //zahodit md tlist[count].buyer = strtok(null, "\t"); tlist[count].date = date_autopsy(strtok(null, "\t")); count++; } fclose(src); return tlist; } transaction *alloc(transaction *tlist, int count) { if (count == 0) { tlist[0].item = (char*)malloc(20 * sizeof(char)); tlist[0].buyer = (char*)malloc(20 * sizeof(char)); } else { tlist = (transaction*)realloc(tlist, count * sizeof(transaction)); tlist[count - 1].item = (char*)malloc(20 * sizeof(char)); tlist[count - 1].buyer = (char*)malloc(20 * sizeof(char)); } return tlist; }
first in main()
, create list
transaction *list = (transaction*)malloc(sizeof(transaction));
then right command, call opening function loads file, tokens line file pieces puts structure. works fine.. when want print(for testing) tlist[count].item inside opening function, prints right thing. when try outside(in main()), prints garbage. somehow works date , price parts of sturcture.. assume "buyer" string broken well. in advance
since overwriting allocated memory local buffer item , bueyr fields not reflected in caller function. modify code below
tlist[count].count = strtok(null, "x") -> strcpy(tlist[count].count, strtok(null, "x"))
tlist[count].buyer = strtok(null, "\t") -> strcpy(tlist[count].buyer , strtok(null, "\t"))
and check tlist[count].date , should allocate memory date , use memcpy copy contents.
since strtok returns null termintated string use of following lines ?
tlist[count].item++;
tlist[count].item[strlen(tlist[count].item)] = '\0';
Comments
Post a Comment