首页 > 解决方案 > 将元素添加到数组,随机数结果

问题描述

我正在尝试使用此功能向现有员工添加图片:

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->imagecount) * sizeof(int));
                newpics[array->imagecount-1] = newpic; 
                newStaff.pic = newpics;
            }
        } 
    }
    return newStaff;
}

但它现在确实像我希望的那样工作。它添加了一张新图片,但只是一个随机数。结果将如下所示:

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

标签: c

解决方案


错误是:

  • array[i]已更新,但imagecountofarray[0]用于选择要更新的元素。
  • array[i].pic更新时array[i].imagecount不更新。newStaff.pic,它被传递realloc()和更新,被初始化为NULL并且与 无关array[i].pic

更正的版本:

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++;
                /* use array[i].pic instead of newStaff.pic and use array[i].imagecount instead of array->imagecount */
                int *newpics = realloc(array[i].pic, (array[i].imagecount) * sizeof(int));
                /* use array[i].imagecount instead of array->imagecount */
                newpics[array[i].imagecount-1] = newpic; 
                /* update array[i].pic instead of newStaff.pic */
                array[i].pic = newpics;
            }
        } 
    }
    return newStaff;
}

推荐阅读