1

I know it is a very simple code, but when printing the elements of the array the 4th element is printed twice like showed bellow.

void printWeekDays(){
char days[7][9] = { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};
for(int i=0; i < 7; i++){
    printf("%s \n",days[i]); 
}

Monday
Tuesday
WednesdayThursday
Thursday
Friday
Saturday
Sunday

Here is my environment: Apple LLVM version 10.0.0 (clang-1000.11.45.5)
Target: x86_64-apple-darwin17.7.0

sepp2k
  • 363,768
  • 54
  • 674
  • 675

2 Answers2

3

"Wednesday" needs char[10] to hold the \0 char.

You get strange behavior because printf will search for \0 in the input string to stop printing but your "wednesday" does not have \0 char appended.

Hence printf goes on printing until it gets \0 that is after printing "thursday".

Change this

char days[7][9]

to

char days[7][10]

or

const char *days[7] //Compiler automatically adjust the size needed to store string literals.
kiran Biradar
  • 12,700
  • 3
  • 19
  • 44
0

This is because "Wednesday" doesn't fit in an array of 9 characters. Sure, there's just 9 letters in Wednesday, but with the null terminator that is put at the end of each string, that's 10 characters. What happens is that the null terinator goes where the T from "Thursday" goes, and when "Thursday" is written to its corresponding place, that null terminator is overwritten. Hence why both are printed after eachother when you try to print Wednesday. It doesn't stop at the end of Wednesday because the next null terminator is at the end of Thursday.

To fix it, change this:

char days[7][9] = {

To this:

char days[7][10] = {

If you don't know about how null terminators work and would like to learn more, you can read about it here.

Blaze
  • 16,736
  • 2
  • 25
  • 44
  • My compiler didn't issue any warning, but I understood the problem. Thanks. – Rodrigo Camargos Nov 29 '18 at 13:25
  • @RodrigoCamargos C compilers don't warn for this bug: it is a defect in the C language. See this: https://stackoverflow.com/questions/52385351/c-string-at-the-end-of-0 – Lundin Nov 29 '18 at 13:45