Home > Blockchain >  warning: format '%s' expects argument of type char problem in a simple program
warning: format '%s' expects argument of type char problem in a simple program

Time:06-19

#include<stdio.h>
#include<stdlib.h>

  
int main()
{
    char str1[20];
    printf("Name: ");
    scanf("%s",&str1);
    printf("Your name is %s",str1);
    return 0;
}

it outputs fine but the the build messages say

warning: format '%s' expects argument of type char ', but argument 2 has type 'char () [20]' [-Wformat=]

CodePudding user response:

str1 has type "array of 20 char" (char[20]). & makes a pointer to the operand. So &str1 has the type "pointer to array of 20 char" (char(*)[20]).

But %s expects the argument to be "pointer to char" (char*) and will store the input characters to consecutive char in memory starting with the location that the argument points to. So &str1 is not the correct type.

Since str1 is an array of char, str1[0] does have just type char and is the first element of the array, where you want scanf to begin storing to and so &str1[0] would for example have type char* and point to the correct char.

Instead you can also just write str1 instead of &str1[0], because arrays will generally (but not when & is applied directly to them) decay to pointers to the first element automatically.


It works exactly the same for printf's %s, where you are using just str1 correctly.

  • Related