【问题标题】:warning: format %s expects type char * but argument 2 has type int警告:格式 %s 需要类型 char * 但参数 2 的类型为 int
【发布时间】:2011-12-06 02:00:31
【问题描述】:

我已经查看了其他相关问题,但没有一个对这个案例有帮助。
我收到了问题标题中列出的警告,main 的代码如下:

int main( int argc, char *argv[] ) {

  char *rows;  
  int i, n;  

  printf("\nEnter the amount of rows in the telephone pad: ");  
  scanf("%d", &n);  

  rows = (char *) malloc( sizeof( char ) * n );  

  printf("\nNow enter the configuration for the pad:\n");  
  for( i = 0; i < n; i++ ) {  
    scanf("%s", &rows[i]);  
    printf("\n\t%s\n", rows[i]);  
  }  

  return 0;    
}

用户将输入一个数字(例如 4),该数字将被扫描到n。该空间被分配给电话垫的行。然后,用户将输入n 行数以配置电话板。一个例子是:

123
456
789
.0.

所以我很困惑为什么我的最后一个printf 语句会出现此错误。

注意:我也尝试了scanf("%s", rows[i]);:仍然出现错误。
注意2:我还是尝试运行该程序。出现分段错误。
注意 3:我的 .c 程序顶部有 #include &lt;stdio.h&gt;#include &lt;stdlib.h&gt;
注意 4:我已经 gcc'ed 程序:gcc -ansi -pedantic -Wall tele.c

感谢您的帮助。

【问题讨论】:

  • 我猜你应该添加“作业”标签。
  • “所以我很困惑”——我对“so”这个词的使用感到困惑,因为你之前写的任何内容都不会影响你收到的错误信息。解决这些问题的方法是放弃所有先入之见,认真对待错误信息以及它们告诉你的内容。在这里,它告诉您%s 需要一个char* 类型的参数,这当然是正确的,它还告诉您您提供的参数不是int 类型......这当然也是正确的,因为rows[i]char,当传递给可变参数函数时会提升为int

标签: c segmentation-fault gcc-warning


【解决方案1】:

rows[i] 不是 char* -- 它不是“字符串”。

(而且你不能在一个字符中放置 3 个字符(加上空终止符)。)

【讨论】:

  • 所以我应该把它改成char **rows,对吗? malloc语句和scanf语句应该怎么做?
  • 如果你想这样,你希望 char** 和 malloc 它是 n * sizeof(char) * the_length_of_string_you_expect_the_user_to_enter
  • 那不适合我。当我运行程序时,我为n输入了5,当我输入'123'时,我得到了(null)打印了5次,然后程序结束了。我将 rows 更改为 char** 并将 malloc 更改为 rows = (char **) malloc( sizeoof( char * ) * n * 11 );,其中 10 是用户应输入的字符串的最大长度,加上空字节。
  • 我确实这样做了,哈哈。我仍然不明白为什么它会打印 null 5 次然后崩溃。
  • 好吧,没关系,我不知何故让它工作了。在某处犯了一个愚蠢的错误:)。感谢您的帮助!
【解决方案2】:

正如其他人指出的那样,您正在为 n 字符分配空间,但您确实需要为 n 行分配空间,每行有 4 个字符(用户输入 3 个字符和一个空终止符)。

有几种方法可以做到这一点。你可以先分配nchar *变量指向行,然后为每行分配4个字节:

int main( int argc, char *argv[] )
{
  char **rows;
  int i, n;

  printf("\nEnter the amount of rows in the telephone pad: ");
  scanf("%d", &n);

  rows = malloc( n * sizeof rows[0] );

  printf("\nNow enter the configuration for the pad:\n");
  for( i = 0; i < n; i++ ) {
    rows[i] = malloc(4);
    scanf("%3s", rows[i]);
    printf("\n\t%s\n", rows[i]);
  }

  return 0;
}

或者,您可以预先分配n 4 字符数组:

int main( int argc, char *argv[] )
{
  char (*rows)[4];
  int i, n;

  printf("\nEnter the amount of rows in the telephone pad: ");
  scanf("%d", &n);

  rows = malloc( n * sizeof rows[0] );

  printf("\nNow enter the configuration for the pad:\n");
  for( i = 0; i < n; i++ ) {
    scanf("%3s", rows[i]);
    printf("\n\t%s\n", rows[i]);
  }

  return 0;
}

【讨论】:

  • 我现在已经解决了这个问题,但是 +1 以获得好的答案:)。非常感谢。
【解决方案3】:

您的 printf 传入的是 char,而不是 %s

你是说获取字符串“rows”中的第 i 个字符。

更重要的是,你的整个技术会严重失败......

我认为您想要一个字符串数组....或者您想将您的 scanf 更改为 %c

【讨论】:

  • 我想要一个字符串数组。你能回答我对热舔答案的评论吗?谢谢。
猜你喜欢
  • 1970-01-01
  • 2013-05-10
  • 2018-11-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多