//使用数组演示sprintf((的示例程序。
我是c的新手,正在努力掌握sprintf使用数组的概念。为什么程序失败,或者打印错误而不是数组d元素?
#include <stdio.h>
int main()
{
char buffer[50];
char d[5]= {1,2,3,4,5};
int i;
for(i=0; i<=6; i++)
{
sprintf(buffer[i], "n num : %s ", i);
}
// The string "sum of 10 and 20 is 30" is stored
// into buffer instead of printing on stdout
for(i=0; i<=6; i++)
{
printf("n %s", buffer[i]);
}
return 0;
}
然而,我得到的错误如下。。
main.c: In function ‘main’:
main.c:13:17: warning: passing argument 1 of ‘sprintf’ makes pointer from integer without a cast [-Wint-conversion]
sprintf(buffer[i], "n num : %s ", i);
^
In file included from main.c:2:0:
/usr/include/stdio.h:364:12: note: expected ‘char * restrict’ but argument is of type ‘char’
extern int sprintf (char *__restrict __s,
^
Segmentation fault (core dumped)
sprintf
期望其第一个参数的类型为char *
,并且是数组中第一个元素的地址,该地址足够大,可以容纳生成的字符串。然而,在行
sprintf(buffer[i], "n num : %s ", i);
buffer[i]
是类型为char
的单个字符,而不是char
的数组。
正如声明的那样,buffer
可以容纳长达49个字符的单个字符串(必须为字符串终止符保留至少一个元素(。在编写时,您的代码期望生成并打印7个不同的字符串,因此buffer
需要声明为
char buffer[7][50]; // hold up to 7 strings of up to 49 characters each
有了这个更改,您的代码应该可以按预期工作。