I want to scan a string and point a char
pointer to this scanned string.
int main(int argc, char *argv[]) {
char *string;
scanf("%s",&string);
printf("%s\n",string);
}
But gives a warning saying
warning: format '%s' expects argument of type 'char *', but argument 2 has type 'char **'
How do I scan a string in a char *
without warnings.
Edit : It worked for the below code with warnings and I drilled down it to the above one so to be very specific.
int main(int argc, char *argv[]) {
int n = 2;
char *strings[2];
for(int i = 0; i < n; i++){
scanf("%s",&strings[i]);
printf("%s\n",&strings[i]);
}
}
First of all, %s
in scanf()
expects a pointer to char
, not a pointer to pointer to char
.
Quoting C11
, chapter §7.21.6.2 / p12, fscanf()
(emphasis mine)
s
Matches a sequence of non-white-space characters.286)
If nol
length modifier is present, the corresponding argument shall be a pointer to the initial element of a character array large enough to accept the sequence and a terminating null character, which will be added automatically. [...]
Change
scanf("%s",&string);
to
scanf("%s",string);
That said, you need to allocate memory to string
before you actually try to scan into it. Otherwise, you'll end up using uninitialized pointer which invokes undefined behavior.
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