gpt4 book ai didi

c - 如何访问结构体数组的第二个元素?

转载 作者:行者123 更新时间:2023-11-30 20:52:01 24 4
gpt4 key购买 nike

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
struct struct1
{
char *name;
short int age;
char *university;
} *person;
person = malloc(3*sizeof(struct struct1));
int headCount=0;
char *line;//temporary string keeper
while(exit)
{
line=readALineFromTXT(); // this is a function it reads only a line at a time from txt and i tested it before
if(line==NULL)
{
break;
}
else
{
person[headCount].name = strtok (NULL,",.-");
person[headCount].age = atoi(strtok (NULL,",.-"));
person[headCount].university = strtok (NULL,",.-");
headCount++;
people = realloc(people,(headCount+2)*sizeof(struct struct1));
}
}


int z=0;
while(z!=headCount) // just to be sure we print it again
{
printf("%d ",z);
printf("%s ",people[z].name);
printf("%d ",people[z].age);
printf("%s \n",people[z].university);
z++;
}
free(people); return 0;
}

输入txt文件是:

P john Smith,34,Stanford   
P Luke Skywalker,18,Empire
P Obi Wan Kenobi,35,LightSide
P Barrack Obama,48,Haravard
P Ben Affleck,22,Stanford
P Osso Buko,18,StackOverFlow

输出是:

0 34 tackOverFlow   
1 18 OverFlow
2 35 OverFlow
3 48 kOverFlow
4 22 ackOverFlow
5 18 StackOverFlow

我找不到我的错误。

最佳答案

将行字符串复制到新分配的内存中,因为 strtok 使用作为参数传递的字符串的内存。阅读 strtok 文档。

试试这个:

while(exit)
{
line=readALineFromTXT(); // this is a function it reads only a line at a time from txt and i tested it before
if(line==NULL)
{
break;
}
else
{
char* newLine = (char*)malloc(strlen(line)+1);
strcpy(newLine,line);
person[headCount].name = strtok (newLine,",.-");
person[headCount].age = atoi(strtok (NULL,newLine));
person[headCount].university = strtok (NULL,newLine);
headCount++;
people = realloc(people,(headCount+2)*sizeof(struct struct1));
}
}

关于c - 如何访问结构体数组的第二个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20922704/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com