输出不正常,求各位高手帮助
题不是很难,读入一系列数据,姓名,ID,年级,并存在数组中。不过在使用搜索的时候发现所有的sur_name和given_name指向最后一个数据,不知为何?#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct
{
char *sur_name;
char *given_name;
int id;
int age;
}str;
str* struct_setup(char surname[32], char givenname[32], int person_id, int person_age) /*use the function to mallocs a struct */
{
str *s;
s=(str *)malloc(sizeof(str));
s->sur_name = (char *)malloc(sizeof(32));
s->given_name = (char *)malloc(sizeof(32));
s->sur_name = surname;
s->given_name = givenname;
s->id = person_id;
s->age = person_age;
return s;
}
str** array_setup() /*use the function to create a array of pointers */
{
str **array;
array = (str **)malloc(sizeof(str*)*10);
return array;
}
str* array_add(str *a,str **b,int num,FILE *out) /*use the function to add the new struct pointers to the array */
{
if (num<10)
{
b[num]=a;
//fprintf(out,"XXXsur_name=%s given_name=%s id=%d age=%d\n\n",b[num]->sur_name,b[num]->given_name,b[num]->id,b[num]->age);
}
if (num>=10)
{
fprintf(out,"\narray is full!\n");
fprintf(out,"num=%d\n",num);
//exit(0);
}
}
void search_by_id(int temp3,str **q,int num,FILE *out) /*use the function to search by id */
{
int i,n=0;
for (i=0;i<num;i++)
{
if (temp3==q[i]->id)
{
fprintf(out,"Search result by id will be:\n");
fprintf(out,"sur_name=%s given_name=%s id=%d age=%d\n\n",q[i]->sur_name,q[i]->given_name,q[i]->id,q[i]->age);
n++;
}
}
if (n==0) fprintf(out,"Nothing matches:%d\n",temp3);
}
int main(int argc, char* argv[])
{
int num=0,n,i;
str **q=array_setup();
FILE *fp=fopen("person_data","r");
FILE *out=fopen("output","w");
char temp1[32],temp2[32];
int temp3,temp4;
while (!feof(fp))
{
fscanf(fp,"%s %s %d %d",temp1,temp2,&temp3,&temp4);
str *p = struct_setup(temp1,temp2,temp3,temp4);
array_add(p,q,num,out);
num++;
fprintf(out,"num=%d\n",num);
fprintf(out,"YYYsur_name=%s given_name=%s id=%d age=%d\n\n",q[num-1]->sur_name,q[num-1]->given_name,q[num-1]->id,q[num-1]->age);
}
fclose(fp);
FILE *search_id=fopen("id","r");
while (!feof(search_id))
{
fscanf(search_id,"%d",&temp3);
search_by_id(temp3,q,num,out);
}
fclose(id);
fclose(out);
return 0;
}