lena
lena

Reputation: 727

How to append elements without overwriting in struct in c

I'm trying to call rrandom to choose one random id and name and put it in buff struct, and second time calling rrandom to choose new random value and putting it also in buff struct as a second item.

How can assign the second value to buff struct without deleting the first item ?

#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");
 } 
}

Upvotes: 0

Views: 95

Answers (1)

Serge Ballesta
Serge Ballesta

Reputation: 149075

You should pass the address of the resulting struct in 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]);
  }
}

You can then use it in your main by replacing your rresult calls with:

rrandom(select, buf);
rrandom(select, buf + 1);

Upvotes: 1

Related Questions