Reputation: 197
The following function :
char **fill(char **array, int *size) {
int i,j;
for ( i = 0; i < *size; i++ ) {
for (j = 0; j < *size; j++ ) {
array[i][j] = '-';
}
}
return array;
}
For input: 5
Gives output:
- - - - -
- - - - -
- - - - -
- - - - -
- - - - -
How to edit the code to get output like this :
0 - - - - -
1 - - - - -
2 - - - - -
3 - - - - -
4 - - - - -
"array" in my function is 2D array of chars of given size n. When i get input of n i tried to allocate every line for n + 1 chars not for n and make the function like this :
char **fill(char **array, int *size) {
int i,j;
for ( i = 0; i < *size; i++ ) {
array[i][0] = 'i';
for (j = 1; j < ( *size + 1 ); j++ ) {
array[i][j] = '-';
}
}
return array;
}
But it does not work.
Input : 5
Output :
i - - - - -
i - - - - -
i - - - - -
i - - - - -
i - - - - -
Upvotes: 1
Views: 39
Reputation: 211135
You are printing the character 'i', but you have to print a character from '0' to '9':
for ( i = 0; i < *size; i++ ) {
array[i][0] = '0' + i; // <-
for (j = 1; j < ( *size + 1 ); j++ ) {
array[i][j] = '-';
}
}
Characters from '0' to '9' have ASCII codes from 48 to 57. '0' + i
means the character with ASCII code 48+i
. The above code works from 0 to 9. If i==10
, it prints ':', because ':' is the character with ASCII code 58 (48+10).
See ASCII table and question Char - ASCII relation.
Upvotes: 1
Reputation: 15642
I think by array[i][0] = 'i';
you meant to write array[i][0] = '0'+i;
...
Keep in mind this is modifying the array. If you wanted to print the array without modifying it, we'd need to see that code.
Upvotes: 0