C结构字符串错误

C结构字符串错误,c,struct,allocation,C,Struct,Allocation,下面是我的一些代码片段,让您了解我的问题 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 = (tran

下面是我的一些代码片段,让您了解我的问题

    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;
}
首先在
main()
中创建列表

transaction *list = (transaction*)malloc(sizeof(transaction));

然后使用正确的命令,调用加载文件的opening函数,然后将该文件中的一行标记为片段,然后放入结构中。一切都很好。。当我要打印(用于测试)打开函数中的tlist[count].item时,它会打印正确的内容。但当我在外面(main()中)尝试时,它会打印垃圾。它在某种程度上适用于结构的日期和价格部分。。我想“买家”的绳子也会断。提前感谢

strtok拥有一个内部静态缓冲区,每次调用后都会填充并返回该缓冲区

像这样的事情:

char *strtok(...)
{
  static char buf[XX];

  // get next token

  return buf;
}
在每次调用之后,您都在有效地分配并覆盖指针指向的数据。 更好的用法是为char*字段分配内存,并对strtok返回的数据使用strcpy

  • 由于您正在使用项的本地缓冲区覆盖分配的内存,因此bueyr字段不会反映在调用者函数中。修改代码如下

    tlist[count].count=strtok(NULL,“x”)->strcpy(tlist[count].count,strtok(NULL,“x”))

    tlist[count]。买方=strtok(NULL,“\t”)->strcpy(tlist[count]。买方,strtok(NULL,“\t”))

    并且还要检查tlist[count].date,您应该为日期分配内存,并使用memcpy复制内容

  • 由于strtok返回空终止字符串,下面几行的用法是什么

    t列表[计数]。项++

    tlist[count].item[strlen(tlist[count].item)]='\0'


  • 这是不正确的。strtok()实际上有一个
    静态字符*
    ,strtok()返回的指针是指向在第一个令牌调用的第一个参数中传递给strtok()的原始内存的指针。strtok()将此内存中的分隔符字符替换为零字节,以便为各个令牌创建以零结尾的字符串。2。我无法正确地分开字符串。它表示“某物”,我想要“某物”,所以我增加了指针。另一行是我试图解决这个问题。我认为那些strotoked字符串没有正确使用,我删除了第二行,使用了您的代码,现在工作正常,非常感谢:)