如何访问struct数组的第二个元素?

时间:2014-01-04 15:16:56

标签: c

#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   

我无法找到我的错误。

1 个答案:

答案 0 :(得分:3)

将行字符串复制到新分配的内存中,因为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));
    }
}