简体   繁体   中英

C Programming printf from an array

Screenshot of the program

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.

  1. I don't know how to print the months in the array. I've tried %s, thinking it was a string but it doesn't work.
  2. List itemI don't understand why we have to use a pointer if monthnames is already an array? I thought they were the same thing, or equivalent? Thanks in advance for your help ! :)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM