spoovy
spoovy

Reputation: 343

2-d array - Why am I not referencing the intended elements?

Real noob question no doubt, but I can't get my head around this behaviour. I initialise a 2-d array, then call a function to print out certain values from it. The program and result are shown below:

int
main(void)
{
    int matrix[3][5] = 
    {
        {14,7,6,55,2},
        {8,33,12,88,24},
        {19,20,21,90,7}
    };

    printArray(3, 5, matrix);

    printArray(2, 3, matrix);

    return 0;
}

void
printArray(int rows, int columns, int matrix[rows][columns])
{
    int i, j;



    for (i = 0; i < rows; i++)
    {
        for (j = 0; j < columns; j++)
            printf("%3i ", matrix[i][j]);

        printf("\n");
    }   



    printf("\n");       
}



 14   7   6  55   2 
 8  33  12  88  24 
 19  20  21  90   7 

 14   7   6 
 55   2   8 

It seems that the second time printArray() is called it continues printing values from the first row on a new line rather than actually accessing the next row. I don't understand this as surely the index values are constant aren't they? (ie matrix[1][2] should be (in this case) 12, not 8.

Thanks in advance.

Upvotes: 1

Views: 69

Answers (2)

NPE
NPE

Reputation: 500247

The following:

void printArray(int rows, int columns, int matrix[rows][columns])

promises the compiler that the third argument has the dimensions rowsxcolumns.

At the same time, the following line breaks this promise:

printArray(2, 3, matrix);

since matrix is 3x5 and not 2x3.

If you only wish to print a subset of rows and columns, you could do something like:

void
printArray(int rows, int columns, int matrix[rows][columns], int max_row, int max_col)
{
    int i, j;

    for (i = 0; i < max_row; i++)
    {
        for (j = 0; j < max_col; j++)
            printf("%3i ", matrix[i][j]);
        printf("\n");
    }           
    printf("\n");       
}

int main(void)
{
   ...
   printArray(3, 5, matrix, 3, 5);
   printArray(3, 5, matrix, 2, 3);
}

Upvotes: 4

Related Questions