The compiler should tell you all you need to know. At https://onlinegdb.com/TTMwKS8GJ:
main.c: In function ‘main’:
main.c:12:15: warning: assignment to ‘char’ from ‘char *’ makes integer from pointer without a cast [-Wint-conversion]
12 | string[0] = "Monday";
| ^
main.c:13:15: warning: assignment to ‘char’ from ‘char *’ makes integer from pointer without a cast [-Wint-conversion]
13 | string[1] = "Tuesday";
| ^
main.c:14:15: warning: assignment to ‘char’ from ‘char *’ makes integer from pointer without a cast [-Wint-conversion]
14 | string[2] = "Wednesday";
| ^
main.c:15:15: warning: assignment to ‘char’ from ‘char *’ makes integer from pointer without a cast [-Wint-conversion]
15 | string[3] = "Thursday";
| ^
main.c:16:15: warning: assignment to ‘char’ from ‘char *’ makes integer from pointer without a cast [-Wint-conversion]
16 | string[4] = "Friday";
| ^
main.c:17:15: warning: assignment to ‘char’ from ‘char *’ makes integer from pointer without a cast [-Wint-conversion]
17 | string[5] = "Saturday";
| ^
main.c:18:15: warning: assignment to ‘char’ from ‘char *’ makes integer from pointer without a cast [-Wint-conversion]
18 | string[6] = "Sunday";
| ^
main.c:23:17: warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘int’ [-Wformat=]
23 | printf ("%s", string[i]);
| ~^ ~~~~~~~~~
| | |
| char * int
| %d
string[]
is an array of 7 characters not 7 strings. You are trying to assign character strings to single characters. C is permissive in that it will let you do that with an implicit cast; but it makes no sense semantically.
What the compiler does not tell you about, but which will cause a run-time error, is the out-of-bounds array access: string[7]
is not a valid array element.
If you did not get similar warnings, fix your compiler settings. If you got warnings, but you ignored them you should either address them before posting the question or ask about the warnings if you do not understand them.
Fixing the errors and improving the "style":
#include <stdio.h>
int main( void )
{
const char* const string[] = { "Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
"Sunday" } ;
for( int i = 0;
i < sizeof(string) / sizeof(*string);
i++ )
{
printf( "%s\n", string[i] ) ;
}
return 0 ;
}
This is now semantically correct and also const correct, devoid of magic numbers and has no temporarily unitialised variables.