首页 > 解决方案 > 向数组添加元素,旧值变为 0 但新显示

问题描述

我已经编写了这个程序,我可以在其中使用他们的名字向员工添加图片。但现在它添加了新值,但已经存在的值变为 0。

这是结果:

type in the name you would like to add pic to 
Anna
type in pic
55
1.Show existing  
2.add pic to a staff
1
Adam    1,2,3,
Anna    0,0,0,55,

其余代码:

typedef struct Staff
{

 char  name[30];
 int   *pic;
 int   imagecount;
 } Staff;


void printStaff(Staff *pStaff)
{
printf("%s    ", pStaff->name);



  if ( pStaff->pic) {
  for(int i=0; i<pStaff->imagecount; i++){

 printf("%d,",pStaff->pic[i]); 
  }
  }

 printf("\n");
 }



void PrintList(Staff aLista[], int staffCount)
 {

for (int i = 0; i < staffCount; i++) {

   printStaff(&aLista[i]);
 }
}

更新代码:

Staff addpic(Staff array[], int staffCount)
{
Staff newStaff = {};    

printf("type in the name you would like to add pic to \n");
fgets(newStaff.name, 30, stdin);


for(int i = 0; i< staffCount; i++) {

    if(strcmp(array[i].name,newStaff.name)==0) {
        if(array[i].imagecount<5) {
            printf("type in pic\n");
            int newpic;
            scanf("%d",&newpic);

            array[i].imagecount++;
            int *newpics = realloc(newStaff.pic, (array[i].imagecount) * sizeof(int));
            newpics[array[i].imagecount-1] = newpic; 
            array[i].pic = newpics;

        }
    } 
}
return newStaff;

其余代码:

 int main(void)
 {
  int staffCount=0;



 int input;


 int test[3]  = {1,2,3};

 Staff myStaff[5] = { {"Adam", test, 3},{"Anna",test,3} };

 staffCount=2;

 do
 {
printf("1.Show existing  \n");

printf("2.add pic to a staff");
printf("\n");
scanf("%d", &input);

switch(input)
{

  case 1:
PrintList(myStaff,staffCount);

break;
  case 2: 
 addpic(myStaff,staffCount);
   break; 

        default: 
            printf("inccorect inpput\n");
            break; 
   }
   }while (input<'1' ||input<'2');


 return 0;
  }

任何帮助表示赞赏,但我是编码新手,所以请记住这一点。

标签: c

解决方案


addpic你做的功能中

int *newpics = realloc(array[i].pic, ...);

一个问题是,如果您对 中初始化的两个元素之一执行此操作array,则array[i].pic指向数组的第一个元素(函数中的数组)。testmain

数组不能重新分配。如果要重新分配内存,还需要动态分配原始内存。


推荐阅读