Home > Net >  C: how to give 2D Array to a function
C: how to give 2D Array to a function

Time:10-31

I want to pass a 2D array already filled with chars to a different method to do something with it. Background: I am trying to implement GameOfLife. And I have already successfully implement the gameboard with a random amount of living cells. But now I want to pass the board(Array) to a different method to continue working with it. How to do so?

//wow das wird hurenshon
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>

void spielStarten(int x, int amountOfLiving){
   
    char feld[x][x];
    
    for(int i = 0; i < x; i  ){
        for(int j = 0; j < x; j  ){
            feld[i][j] = 'o';
        }
    }

    for(int i = 0; i < amountOfLiving; i  ){
        int a = (rand()%x);
        int b = (rand()%x);
        feld[a][b] = 'x';
    }
    
    printf("Gameboard: \n");

    for(int i = 0; i < x; i  ){
        for(int j = 0; j < x; j  ){
            printf("%c ", feld[i][j]);
        }
        printf("\n");
    }

    spielRun(feld);
}

void spielRun(char feld[][]){

    int neighbCount;

    char feldNew[][] = feld[][];

    for(int i = 0; i < x; i  ) {
        for(int j = 0; j < x; j  ) {

            checkForNeighbours(feld[x][y]);
           // in progress
            
        }
    }
}


int main(int argc, char* argv[]){
    srand(time(NULL));
    int x = 16;

    if(argc < 2 || argc > 3){
        printf("2. Argument eine Zahl fuer Feldgroesse eingeben\n");
        printf("1. Argument eine Zahl 0-10 fuer ungefähre prozentuale Belegung mit lebenden 
                Zellen eingeben \n");
        return 0;
    }

    if(argv[2] != NULL){
        x = atoi(argv[2]);
    }

    int i;
    i = atoi(argv[1]);

    i = (x^2)*(0,1*i);

    spielStarten (x,i);
    

    return 0;
}

In the last line of the Method "Spiel starten" i want to give the array to the next Method "spielRun".

Edit: thanks to an other user I found this struture:

void printarray( char (*array)[50], int SIZE )

But it doesn't work for me since I can´t hardcode the number, because the arraysize depends on a user input. thanks!

CodePudding user response:

The difficulty here is that the size of your array is not known statically (once upon a time, your code would even not compile for the same reason).

That, combined with the fact that 2D-arrays are not arrays of 1D arrays (contrarily to what happen when you malloc a int ** and then every int * in it), and so it doesn't make sense not to specify the size when passing it to a function.

When using arrays of arrays (technically, pointers to a bunch of pointers to ints), like this

void f(int **a){
    printf("%d %d %d\n", a[0][0], a[1][0], a[0][1]);
}

int main(){
    int **t=malloc(10*sizeof(int *));
    for(int i=0; i<10; i  ) t[i]=malloc(20*sizeof(int));
    f(t);
}

That code is useless, it prints only unitialized values. But point is, f understands what values it is supposed to print. Pointers arithmetics tells it what a[1] is, and then what a[1][0] is.

But if this 2D-array is not pointers to pointers, but real arrays, like this

void f(int a[][20]){
    printf("%d %d %d\n", a[0][0], a[1][0], a[0][1]);
}

int main(){
    int t[10][20];
    f(t);
}

Then, it is essential that the called function knows the size (or at least all sizes, but for the first dimension) of the array. Because it is not pointers to pointers. It is an area of 200 ints. The compiler needs to know the shape to deduce that t[5][3] is the 5×20 3=103th int at address t.

So, that is roughly what is (better) explained in the link that was given in comments: you need to specify the size. Like I did here.

Now, in your case, it is more complicated, because you don't know (statically) the size.

So three methods. You could switch to pointers to pointers. You could cast your array into a char * and then do the index computation yourself (x*i j). Or with modern enough C, you can just pass the size, and then use it, even in parameters, declaration

void f(int x, int a[][x]){
    printf("%d %d %d\n", a[0][0], a[1][0], a[0][1]);
}

int main(){
    int t[10][20];
    f(t);
}

Anyway, from an applicative point of view (or just to avoid segfault) you need to know the size. So you would have had to pass it. So why not pass it as first parameter (Note that the function in which you have this size problem, spielRun, does refers to a x, which it doesn't know. So, passing the size x would have been your next problem anyway)

So, spielRun could look like this (not commenting in other errors it contains)

void spielRun(int x, char feld[][x]){

    int neighbCount;

    char feldNew[][] = feld[][]; // Other error

    for(int i = 0; i < x; i  ) {
        for(int j = 0; j < x; j  ) {
            checkForNeighbours(feld[i][j]); // Corrected one here
           // in progress
        }
    }
}

And then calls to this spielRun could be

    spielRun(x, feld);

Note that I address only the passing of array of size x here. There are plenty of other errors, and, anyway, it is obviously not a finished code. For example, you can't neither declare a double array char newFeld[][] = oldFeld[][]; nor affect it that way. You need to explicitly copy that yourself, and to specify size (which you can do, if you pass it). I am also pretty sure that i = (x^2)*(0,1*i); does not remotely what you expect it to do.

  • Related