Reputation: 557
So I am writing a simple code to print out each symbol in my string. When compiling it, it gives me an error tough that I do not understand:
The code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main (void) {
char my_string[50];
int i, n;
printf("Type in a string please : ");
scanf("%s", &my_string);
n = strlen(my_string);
for (i = 0;i < n; i++) {
printf("%c",my_string[i]);
}
}
The error it gives:
gcc yl2.c -o Yl2
yl2.c: In function ‘main’:
yl2.c:9:2: warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘char (*)[50]’ [-Wformat=]
scanf("%s", &my_string);
^
What is the problem here?
Upvotes: 1
Views: 1281
Reputation: 8670
remove & sign in scan, it will work Also no need to use string.h here
Upvotes: 1
Reputation: 19232
&my_string
is a pointer to my_string
i.e. a ‘char (*)[50]’
You can either use
scanf("%s", &my_string[0]);
or more conventionally
scanf("%s", my_string);
Upvotes: 2
Reputation: 213276
scanf("%s", &my_string);
should be scanf("%s", my_string);
my_string
is an array, which decays to a pointer when you type it out without [ ].
If you type &my_string
, you get an array pointer, which is strictly speaking not the same thing. That's why the compiler complains.
Upvotes: 2
Reputation: 12658
scanf("%s", &my_string);
there should not be a &
.
Since you have declared char my_string[50];
my_string as character array which is of type char *
which is expecting in scanf()
as the warning states.
Just use, scanf("%s", my_string);
. Base address of the array as argument is sufficient.
Upvotes: 6