Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

format '%s' expects argument of type 'char *'

Tags:

c

#include <stdio.h>
int main(void)
{
    int i,j,k;
    char st;
    printf("enter string\n");
    scanf("%s", st);
    printf("the entered string is %s\n", st);
}

Compiling above program gives me a warning:

warning: format '%s' expects argument of type 'char *', but argument 2 has type 'int' [-Wformat]
palindrom.c:8:1: warning: format '%s' expects argument of type 'char *', but argument 2 has type 'int' [-Wformat]

What am I doing wrong here?

This is what happens when I run it:

$ ./a.out
enter string
kiaaa
the entered string is (null)

Edit:

Here is another version of the code (made char st; into char *st):

#include <stdio.h>
int main(void)
{
    int i,j,k;
    char *st;
    printf("enter string\n");
    scanf("%s", st);
    printf("the entered string is %s\n", st);
}

However, it behaves the same on runtime.

like image 739
Registered User Avatar asked May 24 '12 06:05

Registered User


3 Answers

char st is a single character. Judging by the rest of your code, you probably intended to declare an array of characters:

char st[80];
like image 97
NPE Avatar answered Nov 18 '22 08:11

NPE


scanf needs a pointer to char* to indicate you are scanning a string.

You are supplying a character that's allocated on the stack.

You either want to use a getchar() or make st a char array.

like image 33
Jay D Avatar answered Nov 18 '22 10:11

Jay D


You have a type mis-match.
scanfis not type safe, You need to provide proper type. scanf enables you to get data from the input and you need to tell it what is the type of the data you want it to read. You ask it to read a string by specifying %s by provide it with a character variable.

You need an array:

#define MAX_LENGTH 256
char st[MAX_LENGTH];

As @Jerry rightly points out, You can just simple avoid all the hassle by using:
getline() instead of using scanf

like image 1
Alok Save Avatar answered Nov 18 '22 10:11

Alok Save