c - 为什么我会收到有关此代码示例的警告?什么是适当的?

标签 c

我正在学习一些 C,并且正在阅读来自 this tutorialscanf其中包含以下代码块:

#include <stdio.h>

int main()
{
   char str1[20], str2[30];

   printf("Enter name: ");
   scanf("%s", &str1);

   printf("Enter your website name: ");
   scanf("%s", &str2);

   printf("Entered Name: %s\n", str1);
   printf("Entered Website:%s", str2);

   return(0);
}

但是我收到的警告是:

"Format specifies type 'char *' but the argument has type 'char (*)[20]'

教程有错吗?

最佳答案

这应该适合你:

#include <stdio.h>

int main()
{
   char str1[20], str2[30];

   printf("Enter name: ");
   scanf("%19s", str1);
         //^^   ^ Removed address operator
         //So only the right amount of characters gets read   

   printf("Enter your website name: ");
   scanf(" %29s", str2);
        //^ Added space to catch line breaks from the buffer

   printf("Entered Name: %s\n", str1);
   printf("Entered Website:%s", str2);

   return(0);
}

关于c - 为什么我会收到有关此代码示例的警告?什么是适当的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27805793/

相关文章:

c - 涉及数组的简单C程序无法执行

c - 从 C 中的字符串中删除最常见的单词

c - sched_setaffinity() 是如何工作的?

c++ - 无法使用g++用C++代码编译C库

c - Xcode 上的 Jansson

c - 在 C : I want to take a mix of characters and convert them to lower case

c - 梯形法则问题

c - while 循环内的 if else 语句。(我试图在链表中的给定位置插入一个节点。)

c - 如何在断点上运行 gdb 中的程序函数?

c - 从 C 中的二维数组读取镜像