【问题标题】:Why does the array of elements not get printed under sprintf as below in the code?为什么元素数组没有在 sprintf 下打印,如下代码所示?
【发布时间】: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。

标签: arrays c printf


【解决方案1】:

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

通过该更改,您的代码应该可以按预期工作。

【讨论】:

  • 在这种情况下显示分段错误。
  • @kaylee_96:是在我编辑之前还是之后 - 我没有注意到你从 0 循环到 6,所以你需要一个 7x50 数组。
  • 编辑后。我确实编辑了我的代码以涉及变量 'd' 的使用,因为我注意到它没有在我的程序中使用,但我不确定我应该如何将 d 的元素存储到缓冲区。跨度>
  • @kaylee_96:呸,我年老时失明了——在sprintf 通话中,您需要使用%d 而不是%s,因为iint%s 告诉 sprintfi 解释为 address,而这些值不是有效地址。对此感到抱歉。
  • 解决了,理解了,谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-23
  • 1970-01-01
  • 2021-10-19
  • 2023-01-30
  • 2015-02-16
相关资源
最近更新 更多