Home > Mobile >  Print String Array in C
Print String Array in C

Time:01-16

This is an array of strings in C language. I try to print the elements, but the program doesn't print them. What is the error in the code?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
    char day[7]={"Saturday", "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday","Friday"};
 
    printf("%s\n", day[0]);
}

CodePudding user response:

The statement

char day[7];

declares an array of chars, which can only accommodate 7 bytes — including the null-terminator if it's a string — not 7 strings of indeterminate length.

You can instead declare an array of pointers to char, or char *s, where each pointer points to a sequence of chars in memory.

const char *day[7] = {"Saturday", "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday"};

In memory, it will look something like this:

--------------------------------------
day[0] -> | "Saturday"
--------------------------------------
day[1] -> | "Sunday"
--------------------------------------
day[2] -> | "Monday"
--------------------------------------
day[3] -> | "Tuesday"
--------------------------------------
day[4] -> | "Wednesday"
--------------------------------------
day[5] -> | "Thursday"
--------------------------------------
day[6] -> | "Friday"
--------------------------------------

As day is an array of pointers, you can make it's elements (i.e. pointers) point to somewhere else in memory, but you can't change the string literals themselves.

CodePudding user response:

This declaration

char day[7]={"Saturday", "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday","Friday"};

is invalid.

There is not declared an array of strings. There is declared an array of 7 characters that are initialized by addresses of string literals.

The compiler should issue a message relative to this declaration because there is no implicit conversion from the type char * (the type of the initializing expressions) to the type char.

Instead you should declare a one-dimensional array of pointers like

char * day[7] = {"Saturday", "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday","Friday"};

or better like

const char * day[7] = {"Saturday", "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday","Friday"};

because you may not change string literals (though in C opposite to C string literals have types of non-constant character arrays)

In these declarations the string literals having array types are implicitly converted to pointers to their first characters.

Or a two-dimensional array like

char day[7][10] = {"Saturday", "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday","Friday"};

In this declaration all characters including the terminating zero character '\0' of the string literals are used to explicitly initialize elements of the declared array. All characters of the array that do not have a corresponding explicit initializer will be zero initialized.

  • Related