c - 如何在c中的struct中追加元素而不覆盖
问题描述
我正在尝试调用rrandom
以选择一个随机 id 和名称并将其放入buff struct
,第二次调用rrandom
以选择新的随机值并将其也buff struct
作为第二项放入。
如何在buff
不删除第一项的情况下将第二个值分配给 struct ?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define size 4
typedef struct Org
{
int id[4];
char name[4][7];
}org;
void rrandom(org select[size], ???){
int i,j,r=0;
for (i=0; i<1;i++){
r = (rand() % (4 - 0)) + 0;
for( j=0;j<4;j++){
buf[i].id[j]= select[r].id[j] ;
strcpy(buf[i].name[j], select[r].name[j]);
}}
for ( int i=0; i<2 ;i++){
for(int j=0;j<4;j++){
printf("bname %s bid = %d \n", buf[i].name[j], buf[i].id[j]);
}}
}
void main( )
{
int i,j;
org select[size];
org buf[2];
sprintf(select[0].name[0],"1ello1");
sprintf(select[0].name[1],"1ello2");
sprintf(select[0].name[2],"1ello3");
sprintf(select[0].name[3],"1ello4");
sprintf(select[1].name[0],"2ello1");
sprintf(select[1].name[1],"2ello2");
sprintf(select[1].name[2],"2ello3");
sprintf(select[1].name[3],"2ello4");
sprintf(select[2].name[0],"3ello1");
sprintf(select[2].name[1],"3ello2");
sprintf(select[2].name[2],"3ello3");
sprintf(select[2].name[3],"3ello4");
sprintf(select[3].name[0],"4ello1");
sprintf(select[3].name[1],"4ello2");
sprintf(select[3].name[2],"4ello3");
sprintf(select[3].name[3],"4ello4");
sprintf(select[4].name[0],"5ello1");
sprintf(select[4].name[1],"5ello2");
sprintf(select[4].name[2],"5ello3");
sprintf(select[4].name[3],"5ello4");
printf(" Initial id :\n");
for(i=0;i<4 ;i++)
{
for(j=0;j< 4;j++)
{
select[i].id[j]= j;
} }
rrandom(select,???);
rrandom(select,???);
for ( int i=0; i<2 ;i++){
for(int j=0;j<4;j++){
printf("from main bname %s bid = %d ", buf[i].name[j],
buf[i].id[j]);}
printf("\n\n");
}
}
解决方案
您应该将结果结构的地址传递给rrandom
:
void rrandom(org select[size], struct buff &bf){
int j,r=0;
r = (rand() % (4 - 0)) + 0;
for( j=0;j<4;j++){
bf->bid[j]= select[r].id[j] ;
strcpy(bf->bname[j], select[r].name[j]);
}
for(int j=0;j<4;j++){
printf("bname %s bid = %d \n", bf->bname[j], bf->bid[j]);
}
}
然后,您可以通过将rresult
呼叫替换为以下内容来在主程序中使用它:
rrandom(select, buf);
rrandom(select, buf + 1);
推荐阅读
- c - STM32cube USB VCP 未出现在 Windows 10 上
- amazon-quicksight - 具有来自同一行的值的 quicksight 饼图
- vulkan - 子组调用索引是否映射到 gl_LocalInvocationIndex?
- delphi - 上传图片到 Opencart
- python - 如何通过 Python 使用 Selenium 点击 Google Maps 侧边栏菜单
- c++ - CGAL:要包含哪些标题
- javascript - 在 JavaScript 中,Hack 风格的管道运算符 |> 是否优先于分组运算符 ( )?
- python - 如何通过将数据帧传递给函数并返回包含两者的数据帧来将数据帧附加到另一个数据帧?
- html - csrf 会话令牌缺少烧瓶
- node.js - NodeJS 不能在 Heroku 上工作,但可以在 localhost 上工作