#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.
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];
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.
You have a type mis-match.scanf
is 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With