Home > Mobile >  Wrong print values while iterating 2d char array
Wrong print values while iterating 2d char array

Time:05-18

I am trying to run this code in Arduino IDE. It is printing wrong values.

char daysOfTheWeek[7][4] = {"Sun", "Mon", "Tues", "Wed", "Thur", "Fri", "Sat"};

for(int i=0;i<7;i  ) {
    Serial.print(daysOfTheWeek[i]);
    Serial.print(" ");
}

Serial.println();

Printed values

Sun Mon TuesWed Wed ThurFri Fri Sat

I see this can be fixed by changing the array allocation as following

char *daysOfTheWeek[7] = {"Sun", "Mon", "Tues", "Wed", "Thur", "Fri", "Sat"};

I am fairly new to c . Can anyone help me understand why this is happening?

CodePudding user response:

All string literals have an implicit null-terminator at the end. So, the biggest ones of yours, the "Tues" and the "Thur", are actually contain five characters, like so: "Tues\0" and "Thur\0".

Thus, you either need to increase the dimension of the character array to [5] (resulting in char daysOfTheWeek[7][5]), or you need to use "Tue" and "Thu" as initializers instead.

It may be graphical for you to use the fact that Serial.print() returns the number of bytes written, when you try to print the contents of the daysOfTheWeek in this way.

Meanwhile, for example, in the g compiler your code should give you the error: error: initializer-string for array of chars is too long, pointing to the two problematic string literals mentioned above.

As for the Arduino part, you may want to consider using the String library type.

CodePudding user response:

It is happening because the second dimension of the array is shorter than the longest word.

The code sets the second dimension up to 4. So each print statement will print up to 4 characters. The null character, which is appended to each word, counts as one. Therefore, some words like "Mon" will print correctly (3 characters for the word 1 character for null). Longer words like "Thur" will print without the null characters, so you will see "Thur" and "Fri" back to back as in "ThurFri". To fix this situation, increase the second dimension of the array!

The second option uses pointers for which the compiler knows the length of the word automatically, and therefore, the print will be correct.

There are more ways to do this and which you can read about here: https://www.geeksforgeeks.org/array-strings-c-3-different-ways-create/

  • Related