'How do I put a 2d array of chars into a 2d grid array cells

I'm trying to make a 2048 game right now but I'm having trouble putting my 2d character array into the 2d grid array cells that I made. I'm a beginner programmer learning the basics of C. Here is the code I have so far with the output at the bottom.

    #include <stdio.h>
    #include <ctype.h>
    #include <math.h>
    #define POSX 4
    #define POSY 4
    
    /* Makes a grid array */
    void grid(){
        int r, c, row, col;
        row = col = 4;
    
        for(r = 0; r < row; r++){
            for(c = 0; c < col; c++){
                printf("+---");
            }
            printf("+\n");
            for(c = 0; c < col; c++){
                printf("|   ");
            }
            printf("|\n");
        }
        for(c = 0; c < col; c++){
            printf("+---");
        }
        printf("+\n");
    }
    
    /* Main function */
    int main(){
        char array[POSX][POSY]; //character array
        int x,y;
        for(x = 0; x < POSX; x++){
            for(y = 0; y < POSY; y++){
                array[x][y] = 'A';
            }
        }
        for(x = 0; x < POSX; x++){
            for(y = 0; y < POSY; y++){
                printf("  %c ", array[x][y]);
            }
            printf("\n");
        }
    
        grid(); //Printing out grid array
        
        
        return 0;
    }

Output: I want the As to be within the grid cells

So I want it to look something like for each cell:

+---+
| A |
+---+

Any help is appreciated, thank you!



Solution 1:[1]

You need to merge loops into one set (printing grid and table content at the same time)

Do not use global variables only use function parameters to pass data to the function. The example below will print any size char array in the grid.

void printDiv(size_t cols)
{
    for(size_t col = 0; col < cols; col++)
    {
        printf("+---");
    }
    printf("+\n");
}

void printInGrid(size_t rows, size_t cols, char (*array)[cols])
{
    if(rows && cols && array)
    {
        for(size_t row = 0; row < rows; row++)
        {
            printDiv(cols);
            for(size_t col = 0; col < cols; col++)
            {
                printf("| %c ", array[row][col]);
            }
            printf("|\n");
        }
        printDiv(cols);
    }
}

int main(void)
{
    char array[5][15];
    memset(array, 'A', sizeof(array));
    printInGrid(5, 15, array);
}

https://godbolt.org/z/3PWjsvz8e

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1