-1

I want to fill a matrix, but I need to fill it with pointers, no with the [i][j] structure, I need to use pointers, I've found some valuable info in Fill multiarray (matrix) in C using pointers but, I want to use it within a function, like, a function that initialize the matrix, and I want to add a header-column and a header-row (I'll do it on my own, or i think i can), the thing that i want to make is something like this:


Example

= | 1 | 2 | 3 | 4 |
A | - | - | - | - |
B | - | - | - | - |
C | - | - | - | - |
D | - | - | - | - |


I know how to fill arrays with pointers, (thanks for the guy who solved me that doubt) but idk how the matrix works in c


This is my code

#include <stdio.h>

void initializeMinesWeeper (char *minesweeper) {

}

int main() {
    int rows;
    int columns;
    printf("Dame el número de filas: ");
    scanf("%d", &rows);
    printf("Dame el número de columnas: ");
    scanf("%d", &columns);
    char minesweeper[rows][columns];

    initializeMinesWeeper(minesweeper);
    
    for (int i = 0; i < rows; ++i) {
        for (int j = 0; j < columns; ++j) {
            printf("%c ", minesweeper[i][j]);
        }
        printf("\n");
    }
    return 0;
}

(yes, my homework is a minesweeper) and the [i][j] in fors are just temporal, for checking if it works only

  • Does this answer your question? [C -- passing a 2d array as a function argument?](https://stackoverflow.com/questions/6862813/c-passing-a-2d-array-as-a-function-argument) – Oka Jun 11 '23 at 19:16

1 Answers1

0

First of all, we are going to allocate the matrix dinamically with the following expressions in the main function:

char** minesweeper = (char**)malloc(rows * sizeof(char*));
for (int i = 0; i < rows; i++)
    *(minesweeper + i) = (char*)malloc(columns * sizeof(char));

After that, your initializeMinesWeeper will be implemented as :

    void initializeMinesWeeper(char** minesweeper,const int rows,const int columns) 
    {
        for (int i = 0; i < rows; i++)
        {
            for (int j = 0; j < columns; j++)
                *(*(minesweeper + i) + j) = '-';
        }
    }
  • 2
    The normal syntax for `*(foo + i)` is `foo[i]`. It is much easier to understand. – pmacfarlane Jun 11 '23 at 09:22
  • Also no need to cast result of `malloc()` [Do I cast the result of malloc?](https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) – EsmaeelE Jun 12 '23 at 07:09