1

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 - - - - -
paxie
  • 137
  • 1
  • 2
  • 9
  • You haven't shown the code that actually defines or prints the array. You are showing blanks in the output that not evident in the array setting code. But you can set a digit in the array with `array[i][0] = i + '0';`. – Jonathan Leffler Jan 02 '16 at 20:28

2 Answers2

1

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.

Community
  • 1
  • 1
Rabbid76
  • 202,892
  • 27
  • 131
  • 174
  • Yes that's what i wanted but could you give me a little bit of an explanation what '0' + i (I mean i know the effect but need to know how it actually works ) does? Thanks. – paxie Jan 02 '16 at 19:55
0

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.

autistic
  • 1
  • 3
  • 35
  • 80