【问题标题】:warning: format '%s' expects argument of type 'char *', but argument 2 has type 'char'警告:格式“%s”需要“char *”类型的参数,但参数 2 的类型为“char”
【发布时间】:2018-11-03 21:35:07
【问题描述】:

首先,此代码(PenaltyShootout.c)用于计算给定字符串中以 2 开头的 1 的数量。 “0” - 没有目标, “1” - 目标, “2” - 犯规。

问题:PenatltyShootout.exe 停止工作。

#include <stdio.h>
#include <string.h>

int main()
{
    int T,i;
    char str[100][500];
    int n=0;

没有。的测试用例是没有的。输入不同的字符串以检查代码的工作。

    do
    {
        printf("Enter the number of Test cases(must be between 1 and 100):\n");
        scanf("%d",&T);
    }while(T>100);

我尝试将 str[i][500] 替换为 (char *) str[i][500] 并且警告消失了,但 PenaltyShootout.exe 停止工作。

    for(i=0; i<T; i++)
    {
        printf("Enter the test case %d\n",i);
        scanf("%s",str[i][500]);
    }

    for(i=0; i<T; i++)
    {
        for(int j=0; j<strlen(str[i])-1; j++)
        { 
            if((str[i][j]=='2')&&(str[i][j+1]=='1')==1)
            {
                n++;
            }
        }

这应该打印犯规后的进球数。

        printf("%d\n",n);
    }

   return 0;
}

【问题讨论】:

  • scanf("%s",str[i])
  • "尝试用 (char *) str[i][500] 替换 str[i][500],警告消失了,但 PenaltyShootout.exe 停止工作。" -- 永远不要尝试抛弃错误——发生了非常糟糕的事情......

标签: c pointers


【解决方案1】:

您对 scanf("%s", str[i][500]); 的调用正在将字符串 ("%s") 读入字符 (str[i][500])。

如果您尝试从提示中读取单个字母,则需要像这样切换它:

scanf("%c", &str[i][500]);

"%c"scanf() 知道你想要一个字母,&amp; 告诉它使用内存中字符的地址(str[i][500]str[i] 中的第 501 个位置(当你只分配了 500)) 用于放置它。

如果您正在尝试阅读一个字符串(即一个单词或句子),您需要像这样切换它:

scanf("%s", str[i]);

在这里,您现在将扫描的字符串放入str 中的ith 字符串缓冲区(您已经为其分配了500 个chars)。

【讨论】:

  • 您可能想提到&amp;str[i][500] 立即调用 Undefined Behavior 通过尝试写入到数组末尾 1 后的内存位置....
猜你喜欢
  • 2013-05-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多