Is it a mistake or inappropriateness if I pass a 2D array and the size indicator is in the same function in C?

eg:

void size(int a, int array[a][a]){
..........
}

(I mean, is it okay to pass int a and also have varaible a as the size of the im array, also passing the same function? I would also like to ask if it is possible to pass a 2D array using a double pointer for example: void smthn (int ** array) {...}?)

+4
source share
1 answer

This ad

void size(int a, int array[a][a]);

equivalently

void size(int a, int ( *array )[a] );

where arrayis a pointer to an array of variable length with elements a.

This is a valid syntax in C99.

Here is a demo program

#include <stdio.h>

void f( size_t n, int a[n][n] )
{
    printf( "%zu\n", sizeof( *a ) / sizeof( **a ) );
}

int main(void) 
{
    int a[3][3];
    int b[10][10];

    f( 3, a );
    f( 10, b );

    return 0;
}

Program exit

3
10
+5
source

All Articles