gpt4 book ai didi

c - 向数组添加元素,随机数结果

转载 作者:太空宇宙 更新时间:2023-11-04 03:12:33 27 4
gpt4 key购买 nike

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

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,

最佳答案

错误是:

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

关于c - 向数组添加元素,随机数结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54999925/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com