1

Im creating an array of structs and i need to concatenate a string value with the for loop index.

this is how i create the struct:

typedef struct b
{
char title[30];
char author[40];
int year,price;

}
book_t;

then I create an array using malloc:

int m;
printf ("array size:\n");
scanf("%d",&m);
B= (book_t *) malloc (m*sizeof ( book_t));

and then i need to pass values to fill the array in this form: Title_i, Author_i, 1000+i, 3 * i for i=1...m so im using this for loop:

for(i=1;i<=m;i++){
    B[i-1].title='title_';
    B[i-1].author='author_';
    B[i-1].year=1000_i;
    B[i-1].price=3*i;
    }

any ideas on how can i get the i value of every loop next to the string value for the title and the author field?

Vivian
  • 43
  • 6

1 Answers1

3

Change this loop

for(i=1;i<=m;i++){
    B[i-1].title='title_';
    B[i-1].author='author_';
    B[i-1].year=1000_i;
    B[i-1].price=3*i;
    }

to

for ( i = 0; i < m; i++ )
{
    sprintf( B[i].title, "%s%d", "title_", i + 1 );
    sprintf( B[i].author, "%s%d", "author_", i + 1 );
    B[i].year = 1000 + i + 1;
    B[i].price = 3 * ( i + 1 );
}

I think that instead of 1000_i you mean 1000 + i + 1

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335