Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

#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=]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading