【发布时间】:2021-09-07 09:34:02
【问题描述】:
// 通过使用数组来演示 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(buffer[i], "\n num : %s ", i);至少 buffer[i] 不指向数组。它是 char 类型的标量对象。这个调用完全没有意义。
-
在程序中没有任何地方使用数组 d。