0

I want to change my globally available 2d array to a malloc array and pass it to the following function

I have this 2d array as a global variable

char grid[ROW][COLUMN];

I want to pass it to this functionas a parameter, but using a malloc array

void draw_grid(int row, int col) 
{


     printf(" ");
    for (int c = 0; c < col; ++c) 
    {
        printf(" ");
        printf(" %d", c);
     //   printf(" ");
}

       printf("\n");


    for (int r = 0; r < row; ++r) 
    {    

        printf("%d", r);
        printf("|");

        for(int dot = 0; dot < (row*col); ++dot) 
        {
            grid[r][dot] = ' ';                        


            printf("|");
            printf("%c", grid[r][dot]);

            printf(" ");

            // Dots needs to remain within the grids bounds
            if (dot == (col) - 1) 
            {
                printf("|| \n");
                //printf("\n");
                break;
            }
        }

    }

}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
david
  • 3
  • 4
  • by `malloc array` do you really mean you want to allocate it, or that you need to pass a pointer to the array into your function "like you do for malloc"? – Gem Taylor Oct 23 '19 at 17:48
  • @GemTaylor i just want to pass a pointer to the array – david Oct 23 '19 at 19:13

1 Answers1

1

If the COLUMN is a compile-time constant then the function can be declared like

void draw_grid( char grid[][COLUMN], int row, int col);

and a dynamically allocated array can be obtained the following way

char ( *grid )[COLUMN] = malloc( sizeof( char[ROW][COLUMN] ) );

If the compiler supports variable length arrays then the function can be also declared like

void draw_grid( int row, int col, char grid[][col] );

the dynamically allocated array can be created the same way as above.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335