简体   繁体   中英

2D Array function issue

very new to programming. Trying to read into a function an array of any size... Can't seem to get the code working... "array type has incomplete element type 'int[]'

 void printArray(int array[][], int size, int *sumArrayRight, int *sumArrayBot){
        int i, j;
        for(i = 0; i <size; i++){
            for(j = 0; j <size; j++){
                if(array[i][j] != -1)
                    printf("%3d ", array[i][j]);    
                else
                    printf("  ~ ");
                if(j == size-1)
                    printf("%3d", *(sumArrayRight+i));
            }
            printf("\n");
        }
        for(i = 0; i < size; i++)
            printf("%3d ", *(sumArrayBot+i));
        printf("\n");
    }

It only works if i give the array a size already eg/ int array[10][10] but subsequently that only works if the 2D array being input is of size 10...

You need to use a VLA (Variable Length Array) for this; these were introduced in C99, and made optional in C11, but are still widely available in C11. You can use the -std=c99 compiler flag with gcc to specify that code be compiled to the C99 Standard.

When you declare the VLA, you can use variables for the dimensions. But, be aware that the dimensions can not be changed after declaration:

int my_array[rows][cols];

For this particular case, if the size of the array is unknown at compile time, and determined at runtime, store this size in a variable, and use it to declare the VLA:

size_t arr_sz;
/* Code to determine array size */
int array[arr_sz][arr_sz];

To pass a VLA into a function, you need to pass the array dimensions before the array name in the argument list. Note that size_t is the correct type for array sizes, as this is an unsigned type that is guaranteed to hold any array index. The function prototype should look like:

void printArray(size_t size, int array[size][size], int *sumArrayRight, int *sumArrayBot);

Then the function call would be:

printArray(arr_sz, array, sumArrayRight, sumArrayBot);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM