Replace the first line with spaces
I'm trying to replace the first line with spaces, what is it that is wrong here?
#include <stdio.h>
int main(void){
char text[5][10]={
{'a','a','a','a','a','a','a','a','a','\0'},
{'a','a','a','a','a','a','a','a','a','\0'开发者_JAVA技巧},
{'a','a','a','a','a','a','a','a','a','\0'},
{'a','a','a','a','a','a','a','a','a','\0'},
{'a','a','a','a','a','a','a','a','a','\0'},
};
for (int i=0;i<10;i++){
text[i]=' ';
}
for (int i=0;i<5;i++){
printf("%s\n",text[i]);
}
return 0;
}
You have two problems.
You are only supplying one dimension in your first loop. It should be:
text[0][i]=' ';
You only have 9 'a's, but you are replacing with 10 spaces, so you'll overwrite the null terminator of the first line. so I think you're whole loop should be:
for (int i=0;i<9;i++){ text[0][i]=' '; }
you will have to use
for (int i=0;i<10;i++){
text[0][i]=' ';
}
Now text
will be
text[5][10]={
{' ',' ',' ',' ',' ',' ',' ',' ',' ',' '},
{'a','a','a','a','a','a','a','a','a','\0'},
{'a','a','a','a','a','a','a','a','a','\0'},
{'a','a','a','a','a','a','a','a','a','\0'},
{'a','a','a','a','a','a','a','a','a','\0'},
};
Or
for (int i=0;i<5;i++){
text[i][0]=' ';
}
Now text
will become
text[5][10]={
{' ','a','a','a','a','a','a','a','a','\0'},
{' ','a','a','a','a','a','a','a','a','\0'},
{' ','a','a','a','a','a','a','a','a','\0'},
{' ','a','a','a','a','a','a','a','a','\0'},
{' ','a','a','a','a','a','a','a','a','\0'},
};
Pick whichever solution you wanted. :)
You're not indexing "across", you're indexing "down". Try:
text[0][i] = ' ';
to overwrite the first line's characters.
Also note that you have an Obi-wan; your loop overwrites the terminating character with a space as well.
I'd go one further - you're overwriting the null at the end of the first 'line'. Set your loop to iterate over 0..9:
for (int i=0;i<9;i++){
text[0][i]=' ';
}
I think you should adjust to
text[i][0] = ' ';
for (int i=0;i<9;i++){
text[0][i]=' ';
}
make your array length to 11 like: char text[5][10] to char text[5][11] and change the initialization accordingly.
Chanage your for loop, the condition 'i<10' to 'i<9'
The proble is with index counting.
Its double dimension array and not single dimension ans thats why this will not work.
精彩评论