How does access to strings in an array work?

Asked

Viewed 48 times

1

Create a program that receives the date in numeral and then return it in full.

I tried to do a few times, but I ended up merging my code with one I found from a forum and came out like this:

#include <stdio.h>
#include <stdlib.h>

void Date(int day, int month, int year);

int main(void){
    int day, month, year;
    
    printf("\nDay(1-31): ");
    scanf("%i", &day);

    //limpa o buffer de entrada.
     getchar();

    printf("\nMonth(1-12): ");
    scanf("%i", &month);
    
    //limpa o buffer de entrada.
    getchar();

    printf("\nYear(xxxx): ");
    scanf("%i", &year);

    Date(day, month, year);

    return 0;
}

void Date(int day, int month, int year){
    const char* months[] = {"January", "February", "March", "April",
                               "May", "June", "July", "August",
                               "Setember", "October", "November", "Dezember"};
    system ("clear"); //gnu-linux

    printf("The Date is: %s %dth, %d\n", months[month - 1], day , year);

   
}

I therefore had two doubts about the end of this code:

1 - why [Month - 1]?

2 - why the vector has no value inside to allocate?

3 - why it is necessary to declare const in the char variable?

1 answer

0


1 - why [Month - 1]?

Because arrays begin at 0, So if you typed month 1 you should get index 0, if it was 2 you should get 1, and so on until index 11 which is month 12 that we know.

2 - why the vector has no value inside to allocate?

The compiler can infer this by reading the values that were assigned to it, but there is a value, only it is not visible in the code.

3 - why it is necessary to declare in the variable char?

The text values you have there are in a static area of memory, so an area that cannot be modified. Literals string are always like this. It is not a location you can manipulate, so if you try the application break. If you put const The compiler knows that it cannot move there so it makes an error when compiling if it tries to modify something there, and this error is much better than an error when it is running. See more in Where does the memory space required for each element in a C string array come from?. Also: Change of char variable content.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.