Search code examples
arrayscfor-loopmultidimensional-arrayfunction-declaration

My 2d array is being assigned the wrong values


Im trying to write a function to populate a 2D array with random values between min and max. However, it's only properly giving the values to the first row and garbage values to the rest.

Here's the code:

#include <stdio.h>
#define COL 100
#include <stdlib.h>

void PopulateArray2D(int Mat[][100], unsigned int rowsize, unsigned int colsize, int min, 
int max);

int main(){
    int Mat[5][5];
    PopulateArray2D(Mat,5,5,1,10);

    for(int i=0;i<5;i++){//prints 2d array
        for(int j=0;j<5;j++){
            printf("%d ",Mat[i][j]);
        }
        printf("\n");
    }
}

void PopulateArray2D(int Mat[][100], unsigned int rowsize, unsigned int colsize, int min, 
    int max){//puts random values into the array
    int randNum = 0;
    for(int i=0;i<rowsize;i++){
        for(int j=0;j<colsize;j++){
            randNum = rand()%(max-min + 1) + min;
            Mat[i][j] = randNum;
        }
    }
}

Output was:

4 7 8 6 4 
22032 15775231 0 194 0 
673948839 32766 673948838 32766 1067381581 
22032 -1714622520 32694 1067381504 22032 
0 0 1067380928 22032 673949104

Solution

  • You are using pointers of incompatible types.

    Within the function main the array is declared like

    int Mat[5][5];
    

    but in the function PopulateArray2D it is declared like

    void PopulateArray2D(int Mat[][100], unsigned int rowsize, unsigned int colsize, int min, 
        int max);
    

    So this is the problem. That is the array used as an argument of the function is implicitly converted to the type int ( * )[5] while the function parameter is adjusted to the pointer type int ( * )[100].

    Either declare the function like

    void PopulateArray2D(int Mat[][5], unsigned int rowsize, unsigned int colsize, int min, 
        int max);
    

    Or if the compiler supports variable length arrays then declare the function like

    void PopulateArray2D( unsigned int rowsize, unsigned int colsize, int Mat[][colsize], int min, 
        int max);
    

    and call it like

    PopulateArray2D(5,5,Mat,1,10);