2014-10-20 29 views
1

我创建了一个结构数组,我需要将一个字符串值与for循环索引连接起来。C中的连接0

这是如何创建的结构:

​​

然后我使用malloc创建阵列:

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

,然后我需要传递的值来填充所述阵列中这种形式: Title_i, Author_i, 1000 + i, 3 * i for i = 1 ... m so im using this for循环:

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; 
    } 

关于如何获得每个循环旁边的标题和作者字段的字符串值的i值的任何想法?

+0

如何itoa功能? void * itoa(int input,char * buffer,int radix) – antonpp 2014-10-20 18:02:40

+1

'sprintf(B [i-1] .title,“title_%d”,i);' – chux 2014-10-20 18:03:16

+2

@Anton:既不是C也不是POSIX。顺便说一句:[不要投出malloc(和朋友)](http://stackoverflow.com/q/605845)的结果,字符文字''A''不是字符串文字''字符串''。 – Deduplicator 2014-10-20 18:04:37

回答

3

更改这个循环

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; 
    } 

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

我认为与其1000_i你的意思1000 + i + 1

+0

为什么当''title_“'作为一个arg提供给'sprintf'时它可能已经在格式化字符串中? – Alnitak 2014-10-20 18:14:52

+1

@Alnitak我更喜欢我使用的记录,因为不是“title_”,可以有任何变量。这是一个更普遍的方法。 – 2014-10-20 18:16:24