Reputation: 397
I wanted to create a program where you would give input and it would give an output based on the input, but I've been having some trouble with the input part. I first made an uninitialized string and wanted the input to be stored in it. But when I compile, it shows this error:
format ‘%c’ expects argument of type ‘char *’, but argument 2 has type ‘char (*)[0]’
I've looked online, but was not able to get an answer on how to fix this.
My code so far below (In C):
#include <stdio.h>
#include <stdlib.h>
int main() {
char string[] = "";
scanf("%c", &string);
}
Upvotes: 1
Views: 813
Reputation: 16550
regarding;
scanf("%c", &string);
The variable string
is an array. In C, a 'bare' reference to an array degrades to the address of the first byte of the array. So, the call to scanf()
parameter &string
is asking for the address of an address.
Usually the compiler will output a warning (as you have seen) but will produce the correct code. To avoid this problem, remove the &
from the parameter when the parameter is a 'bare' reference to an array. I.E.
scanf("%c", string);
Even better, use:
scanf("%c", &string[0]);
For robust code, always check the returned value from any of the scanf()
family of functions. In general, they return the number of successful input format conversion specifiers. so an even better example would be;
if( scanf("%c", &string[0]) != 1 )
{
fprintf( stderr, "scanf for first char of array -string- failed" );
}
This kind of error is (usually) not recoverable, so normally the code would be:
if( scanf("%c", &string[0]) != 1 )
{
fprintf( stderr, "scanf for first char of array -string- failed" );
exit( EXIT_FAILURE );
}
where both exit()
and EXIT_FAILURE are exposed in the header file: stdlib.h
Upvotes: -1
Reputation: 1
your problem statement is "I wanted to create a program where you would give input and it would give an output based on the input"
You can try something like this:
#include <stdio.h>
#include <stdlib.h>
#define MAX_LEN 50
int main(){
char string[MAX_LEN+1];
//fgets is safe & would read whitespaces
fgets(string, MAX_LEN, stdin);
printf("%s", string);
return 0;
}
Upvotes: 0
Reputation: 3573
&string
is a pointer to an array, just passing string
is sufficient. string
has length 1 and will fit a single character, but don't try to interpret it as a string because it will not be null-terminated.
#include <stdio.h>
#include <stdlib.h>
int main() {
char string[] = "";
scanf("%c", string);
}
Alternatively, you could do this. It is equivalent and some say it is more readable.
int main() {
char string[] = "";
scanf("%c", &string[0]);
}
Upvotes: 4