Reputation: 125
How come Line 1
and Line 2
have more than ten x(s) when the loop should end at ten given the condition of ii < 10
?
I am trying to understand how these two dimensional arrays work, any advice is appreciated.
#include <stdio.h>
int main()
{
char name[3][10];
for(int i = 0; i < 3; i++){
for(int ii = 0; ii < 10; ii++){
name[i][ii] = 'x';
}
}
printf("Line 1: %s.\n", name[0]);
printf("Line 2: %s.\n", name[1]);
printf("Line 3: %s.\n", name[2]);
return 0;
}
FIX:
Thanks to everyone's comments I managed to fix the code. The problem was that I was not reserving one space for the NULL terminator at the end of the array. Since I wanted ten x(s), the solution is to increase the size of the two dimensional array so that it has space for the NULL terminators.
#include <stdio.h>
int main()
{
char name[4][11];
for(int i = 0; i < 3; i++){
for(int ii = 0; ii < 10; ii++){
name[i][ii] = 'x';
}
}
printf("Line 1: %s.\n", name[0]);
printf("Line 2: %s.\n", name[1]);
printf("Line 3: %s.\n", name[2]);
return 0;
}
Upvotes: 1
Views: 92
Reputation: 44274
As it has been discussed in comments, the problem with your code was that you didn't add a NUL to terminate the strings.
However, I'll post an answer as your fix isn't really a fix
Two things to mention:
You don't need to extend the dimension of the array to [4][11]
but only to [3][11]
. It's only the number of chars in each string that need to be increased to make room for the termination. Changing [3]
will give you room for an extra string and that is not what you are looking for. So use [3][11]
Your fix still doesn't add the NUL terminator. Remember that a local variable isn't automatic initialized so you need to do it yourself. In other words - you need some code that explicit sets name[i][10]
to NUL.
This is how memory is looking in your original code, your fix and how you really want it.
Below is two ways to get what you want.
Option 1:
char name[3][11];
for(int i = 0; i < 3; i++){
for(int ii = 0; ii < 10; ii++){
name[i][ii] = 'x';
}
// Add NUL to the end to get a correct C style string
name[i][ii] = '\0';
}
Option 2:
// Explicit initialize the whole array to zero
char name[3][11] = { 0 };
for(int i = 0; i < 3; i++){
for(int ii = 0; ii < 10; ii++){
name[i][ii] = 'x';
}
}
I prefer option 1 but option 2 will also do the job.
Upvotes: 3