Search code examples
arraysccharinitializationstring-literals

Print String Array in C


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]);
}

Solution

  • 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.