将元素添加到数组,随机数结果

时间:2019-03-05 09:52:42

标签: c

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

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,

1 个答案:

答案 0 :(得分:1)

错误是:

  • array[i]已更新,但是imagecount中的array[0]用于选择要更新的元素。
  • array[i].picarray[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;
}