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,
解决方案
错误是:
array[i]
已更新,但imagecount
ofarray[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;
}
推荐阅读
- vue.js - 模拟函数在 Vue 测试中没有返回值
- python - 如何处理棋盘格中的鼠标光标移动事件?
- c# - RabbitMq like 与 Masstransit 的话题交流
- powerapps - 共享 Power App 时无法将安全角色分配给 Dataverse 表
- python - 使用列表作为函数的参数
- java - Spring Batch JpaTransactionManager 会影响 Spring Data JPA?
- python - 我不会在我的游戏石头,纸和剪刀中输
- oauth2-playground - 多个并发访问代码请求/上传
- php - MySQL - 按星期几比较几个月的数据 - 例如每个月的第一个星期六的会话
- swift - 如何在 Xcode 13 中使用图像文字