c - 向数组添加元素,旧值变为 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;
}
任何帮助表示赞赏,但我是编码新手,所以请记住这一点。
解决方案
在addpic
你做的功能中
int *newpics = realloc(array[i].pic, ...);
一个问题是,如果您对 中初始化的两个元素之一执行此操作array
,则array[i].pic
指向数组的第一个元素(函数中的数组)。test
main
数组不能重新分配。如果要重新分配内存,还需要动态分配原始内存。
推荐阅读
- scheme - flatmap 的最直接用法
- node.js - Mern 应用程序在开发模式下完美运行,但在生产模式下显示“c.map 不是函数”
- c - 我可以释放在 C 中递归的每个步骤中生成的 malloc 吗?
- java - 执行maven打包的jar时ClassNotFound
- php - 无法在 magento 中使用 SKU 连字符进行高级搜索?
- python - 插入记录 Python 'tuple' 无法转换为 MySQL 类型
- .net - 以较小的尺寸显示新打开的窗口,如弹出窗口
- java - 如何使密码的输入字段变成星号?
- jspdf - 如何在jspdf中为表格行添加颜色?
- c# - 如何使用 C# 在 Linux 中杀死特定用户的所有进程?