如何在struct中附加元素而不覆盖 [英] How to append elements without overwriting in struct
本文介绍了如何在struct中附加元素而不覆盖的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在这段代码中,我试图调用
In this code I'm trying to call
rrandom
来选择一个随机id和名称并将其放入buff结构中,第二次调用
to choose one random id and name and put it in buff struct , and second time calling
rrandom
选择新的随机值并将其放在buff结构中,如何将第二个值赋值给buff struct而不删除第一个?
我尝试过:
to choose new random value and putting it also in buff struct , how can assign the second value to buff struct without delete the first one?
What I have tried:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define size 4
typedef struct Org
{
int id[4];
char name[4][7];
}org;
struct buff
{
int bid[4];
char bname[4][7];
};
struct buff buf[2];
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].bid[j]= select[r].id[j] ;
strcpy(buf[i].bname[j], select[r].name[j]);
printf("------r=%d \n" ,r);
}}
for ( int i=0; i<2 ;i++){
for(int j=0;j<4;j++){
printf("bname %s bid = %d \n", buf[i].bname[j], buf[i].bid[j]);
}}
}
void main( )
{
int i,j;
org select[size];
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].bname[j], buf[i].bid[j]);
}
printf("\n\n");
}
}
推荐答案
正确的方法是修改rrandom
函数,以便接受指向您打算修改的struct buff
的指针。例如
The proper way to do that is modify therrandom
function in order to accept a pointer to thestruct buff
you intend to modify. E.g.
void rrandom( org select[], struct buff * pbuff)
{
//...
}
然后适当地调用它,例如
And then call it appropriately, e.g.
rrandom(select, &buf[0]); // fill the first array item
rrandom(select, &buf[1])); // fill the second array item
昨天我向你解释了解决方案后,你为什么还要这样做?
见在C中使用函数的问题 [ ^ ]。
Why are you still doing this, after I explained the solution to you yesterday?
See Issue in using function in C[^].
这篇关于如何在struct中附加元素而不覆盖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文