Search code examples
arrayscpointersparametersfunction-definition

How do I pass in a 2d array I made from main into another function in C


so I'm trying to make a 2d binary matrix that is the size provided by stdin and that has randomly assigned indexes for the 0 and 1, however, their cannot be more than size/2 zeroes or ones.

For example

an input of 2

could output

1 0

0 1

Now I was going to originally just use the argument int arr[][n] in init but this idea failed since passing in the matrix just resulted in my program going on some sort of an infinite loop when I attempted to access matrix again inside of the main function. I believe this happened because the lifespan of matrix expired when init concluded? So my question here is why is what I'm doing now producing the below error and how can I fix this up?

note: expected ‘int * (*)[(sizetype)(n)]’ but argument is of type ‘int (*)[(sizetype)(dim)][(sizetype)(dim)]’
    7 | int init(int n, int* arr[][n]);

My code

#include <stdio.h>
#include <time.h>
#include <stdlib.h>



int init(int n, int* arr[][n]);
int main(){
    time_t t;
    srand((unsigned) time(&t));
    int dim;
    printf("Enter a positive even integer: ");
    scanf("%d",&dim);
    if(dim<2||dim>80){
        return 1;
        }
    int matrix[dim][dim];
    init(dim,&matrix);  
    
    
    
    return 0;
    }

int init(int n, int* arr[][n]){
    int numZeroes,numOnes;
    int zero_or_one;
    for(int row=0;row<n;row++){
        numZeroes=0;
        numOnes=0;
        for(int col=0;col<n;col++){
            if(numZeroes<n/2 && numOnes<n/2){
                zero_or_one=rand()%2;
                *arr[row][col]=zero_or_one;
                if(zero_or_one==1){
                    numOnes++;
                    }
                if(zero_or_one==0){
                    numZeroes++;
                    }
                }
            else{
                if(numZeroes==n/2 && numOnes<n/2){
                    *arr[row][col]=1;
                    }
                if(numZeroes<n/2 && numOnes==n/2){
                    *arr[row][col]=0;
                    }
            }
        }
        }
    
    for(int row=0;row<n;row++){
        for(int col=0;col<n;col++){
            printf("%d ",*arr[row][col]);
            
        }
        printf("\n");
    }
    return 0;
    }

Solution

  • The function should be declared like

    void init(int n, int arr[][n]);
    

    (the return type int of the function does not make a great sense.)

    and called like

    init(dim, matrix);
    

    Within the function instead of statements like this

    *arr[row][col]=zero_or_one;
    

    you have to write

    arr[row][col]=zero_or_one;