Grammar inquiries when used as two-dimensional array parameters

Asked 2 years ago, Updated 2 years ago, 103 views

1) When using a two-dimensional array as a parameter for a function, why is it that the horizontal size should be specified...? 2) Usually, we receive separate values of col and row that tell us the size of the array as follows, but can't we omit array size 5? 3) If the row value is 6... Should I also modify the function to intarr[][6] every time?

ex)

void print2DArray(int arr[][5], int col, int row)    
{
    for (int i = 0; i < row; i++)
    {
        for (int j = 0; j < col; j++)
        {
            printf("%d ", arr[i][j]);
        }

        printf("\n");
    }
}

c++ array function

2022-09-22 20:09

1 Answers

type arr[32];
  arr        arr+1     arr+2
   .__________.__________.__________.__________.__
   |          |          |          |          |
   .__________.__________.__________.__________.__
    \___  ___/
         v   
     sizeof(type)

int arr[32][4];
 &(arr[0])  &(arr[1])  ..
  arr        arr+1     arr+2
   .__________.__________.__________.__________.__
   |          |          |          |          |
   .__________.__________.__________.__________.__
    \___  ___/
         v   
     sizeof(int[4])
     = = 4*sizeof(int)

It becomes like this. However, if you move on to the function call factor, the array variable only goes over the pointer value, so the called side doesn't know how many units of pointer computation should be done when accessing the element of the array. So, in a multidimensional array, if you omit the size of the top array, you cannot omit the size of the subarray.

Added 2019-04-10

An example of a function that can be used for two-dimensional arrays of different sizes.


int print_array(int *arr, int n_row, int n_col)
{
    int i, j;
    for (i = 0; i < n_row; i++)
    {
        for (j = 0; j < n_col; j++)
        {
            printf("%d\t", *(arr + i*n_col + j));
        }
        printf("\n");
    }
    printf("----------------\n");
    return 0;
}

int main()
{
    int a[2][2] = { {0, 1}, {2, 3} };
    int b[4][3] = {
        {0, 0, 0}, {1, 1, 1}, {2, 2, 3}, {3, 3, 4} 
    };

    print_array((int*)a, 2, 2);
    print_array((int*)b, 4, 3);
    return 0;
}


2022-09-22 20:09

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.