regarding:
#include<stdio.h>
int main(void)
{
char a[9];
scanf("%s",&a);//scanf("%s",a)
printf("%s",&a);//printf("%s",a) they all can run correctly!
for(int i=0;i<9;i++)
{
printf("%c;",a[i]);
}
return 0;
}
When compiling, always enable the warnings, then fix those warnings. ( for gcc
, at a minimum use: -Wall -Wextra -Wconversion -pedantic -std=gnu11
) Note: other compilers use different options to produce the same results.
The posted code results in three(3) warning messages from the compiler
gcc -O1 -ggdb -Wall -Wextra -Wconversion -pedantic -std=gnu11 -c "untitled2.c"
untitled2.c: In function ‘main’:
untitled2.c:5:13: warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘char (*)[9]’ [-Wformat=]
scanf("%s",&a);//scanf("%s",a)
~^ ~~
untitled2.c:6:14: warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘char (*)[9]’ [-Wformat=]
printf("%s",&a);//printf("%s",a) they all can run correctly!
~^ ~~
untitled2.c:5:5: warning: ignoring return value of ‘scanf’, declared with attribute warn_unused_result [-Wunused-result]
scanf("%s",&a);//scanf("%s",a)
^~~~~~~~~~~~~~
Compilation finished successfully.
The final statement: "Compilation finished successfully.", when there are warning messages, only means the compiler produced some 'work around' for the problems, That does not mean the compiler produced the code that you wanted.
regarding:
for(int i=0;i<9;i++)
{
printf("%c;",a[i]);
}
if the input from the user was less than 8 bytes, then some trash/garbage bytes will be output.
Suggest:
for( int i=0; a[i]; i++ ) // stops on NUL byte
{
printf("%c;",a[i]);
}
so only the user input and not the uninitialized bytes be output.
Even better, since the call to scanf()
with %s
will have NUL terminated the input is to use the single statement:
printf( "%s\n", a );
OT: When calling any of the scanf()
family of functions, always check the returned value (not the parameter values) to assure the operation was successful. Note: those functions return the number of successful 'input format conversion' specifiers (or EOF). Suggest: (after syntax corrections and error checking added)
if( scanf("%8s",a) != 1 )
{ // error occurred
fprintf( stderr, "scanf for input data failed\n" );
exit( EXIT_FAILURE );
}