In this program, the user inputs the date and month of the year in terms of numbers. The output has to be in letters. I can't change the variables.
For printing month name just use
printf("%s", monthnames[month]);
instead of
printf("%c", *monthnames[month]);
The latter just prints first character in some month.
monthnames
is an array of pointers to char
. So you can use each element in that array to point to a C string - as it is the case in your code.
Note: beware of indexes, in code comments you suggest April is 4-th month. Then December will be 12-th, but your array can have only maximum index 11.
Your variable monthnames is an array of pointers to null-terminated strings. This means that monthnames[month]
is a pointer to a null-terminated string which you can printf with %s and *monthnames[month]
is the first char in that string which you can print with %c. *pointer
means the variable that pointer
is pointing to.
It might also be a good idea to check user input before using month
to index the array. If a user enters a big month like 20 or a negative month your program will probably segfault without such a check.
Get a string from an array like that using monthnames[month]
.
You see, monthnames is an array (but we are denoting it like a pointer) of arrays of char
s. Since we are treating the pointer like an array here, we don't need to dereference it.
You also probably want to declare your things as const
if you are not planning to change them. It's not required, but it's good practice.
I made a program to test this in case you don't believe me:
#include <stdio.h>
int main(void)
{
const char* monthnames[2] = { "Jan", "Feb" };
printf("%s\n", monthnames[0]);
printf("%s\n", monthnames[1]);
return 0;
}
Output:
Jan
Feb
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.