Reputation: 111
I am trying to create a character array with X number of characters.
I need the first X-1 characters to be spaces and I need the Xth character to be an *
.
I have written the following:
int i = 0;
int X = 5;
char spaces[X]; //In this case X is 5 so the array should have indexes 0 - 4
for(i = 0; i < X; i++) {
spaces[i] = '*'; //I start by setting all 5 char's equal to '*'
printf("spaces = '%s'\n", spaces); //This was to make sure it ran the correct # of times
}
The output of this segment is the following, the 'gh' is different every time:
spaces = '*gh'
spaces = '**h'
spaces = '***'
spaces = '****'
spaces = '****'
why does spaces only grow to 4 instead of 5 characters? Shouldn't spaces[4] = '*'; have been called?
After setting the whole string equal to '*' I run a second for loop:
for(i = 0; i < X-1; i++) {
spaces[i] = ' ';
}
which should then set everything but the Xth character equal to ' ', but since the string is acting like its only X-1 characters long, the whole thing is set to spaces and it comes out like this
spaces = ' ';
4 spaces, when I need 4 spaces followed by an *
.
Upvotes: 0
Views: 60
Reputation: 115
In order to set first X-1 characters to be spaces and the Xth character to be an . This will always have the last character a ''
for(i = 0; i < X-1; i++) {
spaces[i] = ' ';
spaces[i+1] = '*';
printf("spaces = '%s'\n", spaces);
}
Upvotes: 0
Reputation: 35154
You are missing the string termination character \0
, which is needed once you want to print your array as a string using printf("%s",...)
.
So make your array one item larger than the items you want to print, and initialize it with 0
, such that everything you write into the array will at the end be a valid string. Otherwise you yield undefined behaviour:
int main (void)
{
#define X 5
int i = 0;
char spaces[X+1] = { 0 };
for(i = 0; i < X; i++) {
spaces[i] = '*';
printf("spaces = '%s'\n", spaces);
}
}
Upvotes: 1