使用struct pointer函数创建struct数组的元素

时间:2014-05-17 16:12:14

标签: c arrays pointers struct

我一直在尝试用指向结构数组的指针编写一个函数。在调用它之后,我的数组应该有一个新的struct元素。

这是我的功能由你们的建议改变

void addPic(pic *picture_Record, int picNumber){


pic tmp_Pic;
char tmp_fileName[100];
char tmp_description[100];
char tmp_location[100];

if (picture_Record[picNumber].description ==NULL || picture_Record[picNumber].fileName ==NULL||picture_Record[picNumber].location==NULL)
    return;

printf("Enter: Picture Name, Picture Description, Picture Location, Picture People(int)\n");
scanf("%s%s%s%d",tmp_fileName, tmp_description, tmp_location, &picture_Record[picNumber].peopleCount);  

tmp_Pic.fileName = (char*)malloc(strlen(tmp_fileName)+1);
tmp_Pic.description=(char*)malloc(strlen(tmp_description)+1);
tmp_Pic.location = (char*)malloc(strlen(tmp_location)+1);
strcpy(tmp_Pic.fileName, tmp_fileName);
strcpy(tmp_Pic.description, tmp_description);
strcpy(tmp_Pic.location, tmp_location);

picture_Record[picNumber] = tmp_Pic;
free(tmp_Pic.fileName);
free(tmp_Pic.description);
free(tmp_Pic.location);
printf("\nInput Done!\n");

这就是我所说的。

 int picNumber = 0
 pic pictureRecord[Maximun_Picture +1]= { "" };

 addPic(&pictureRecord[picNumber], picNumber);
 picNumber++;
 //testing
 printf("%s",pictureRecord[0].location)

这是我的结构。

  typedef struct picture_Data
  {
    char* fileName;
    char* description;
    char* location;
    int peopleCount;
  }pic;

它不起作用并将我打印为第一个元素的位置。为什么?有人可以帮助我。

2 个答案:

答案 0 :(得分:2)

问题是这一行

scanf("%s%s%s%d",pic_tmp.fileName, pic_tmp.description, pic_tmp.location, &pic_tmp.peopleCount);

假设pic.tmpfileNamedescriptionlocation分配了足够的空间。然而,这些都不是真的,因为所有三个字段都保持未初始化。

为了解决这个问题,请更改代码以将字符串读入临时缓冲区,然后将其复制到动态分配的字符串中。

以下是fileName的执行方式;你需要为这三个人做同样的事情:

char tmp_fileName[100];
char tmp_description[100];
char tmp_location[100];
scanf("%99s%99s%99s%d",tmp_fileName, tmp_description, tmp_location, &pic_tmp.peopleCount);
pic_tmp.fileName = malloc(strlen(tmp_fileName)+1);
strcpy(pic_tmp.fileName, tmp_fileName);
...

您也可以使用单个作业复制struct

picture_Record[picNumber] = pic_tmp;

不要忘记在每个free的所有三个成员上调用struct以避免内存泄漏。

答案 1 :(得分:0)

You should first have to allocate memory

 void addPic(pic *picture_Record, int picNumber){
 pic pic_tmp;  
 printf("Enter: Picture Name, Picture Description, Picture Location, Picture
 People(int)\n");
 pic_tmp.fileName = (char *)malloc(5);    
 picture_Record[picNumber].fileName = (char *)malloc(5);  
 scanf("%s%d",pic_tmp.fileName, &pic_tmp.peopleCount);  
 printf("\nInput Done!\n");  
 strcpy(picture_Record[picNumber].fileName, pic_tmp.fileName);  
 //picture_Record[picNumber].fileName = pic_tmp.fileName;  
 picture_Record[picNumber].description= pic_tmp.description;  
 picture_Record[picNumber].location = pic_tmp.location;  
 picture_Record[picNumber].peopleCount = pic_tmp.peopleCount;  
 printf("%s,%s",pic_tmp.fileName,picture_Record[picNumber].fileName );  
 }