0

So, I am trying to create a text-mode minesweeper for a university project and I am trying to initialize an array with *, for mines.

//function declaration
void populateArray(char *, int *, int *, int *);

//pointer declaration
char *table = (char *)malloc((*numberOfRows) * (*numberOfColumns) * sizeof(char));
    if (table == NULL)
        printf("Error in memory allocation");
    
    char helper[*numberOfRows][*numberOfColumns];
    table = &helper[0][0];

//function call
populateArray(table, numberOfMines, numberOfRows, numberOfColumns);

//function definition
void populateArray(char *array, int *mines, int *rows, int *columns)
{
    int i, j, sum;
    sum = 0;
    char helper[*rows][*columns];
    array = &helper[0][0];
    
    for(i = 0; i < *rows; i++)
    {
        for(j = 0; j < *columns; j++)
        {
            if(sum < *mines)
            {
                array = array + i + j;
                sum++;
            }
            else
            {
                array = array + i + j;  
            }
            printf("%c\n", helper[i][j]);
        }
    }
}

The helper function works as expected if I formulate it like this

void populateArray(char *array, int *mines, int *rows, int *columns)
{
    int i, j, sum;
    sum = 0;
    char helper[*rows][*columns];
    array = &helper[0][0];
    
    for(i = 0; i < *rows; i++)
    {
        for(j = 0; j < *columns; j++)
        {
            if(sum < *mines)
            {
                helper[i][j]= '*';
                sum++;
            }
            else
            {
                helper[i][j]= ' ';  
            }
            printf("%c\n", helper[i][j]);
        }
    }
}

But still, the problem with the hieroglyphics persists in the main function. I suppose it has to do with the memory allocation part, that the pointers are associated with.

  • `array = &helper[0][0];` That's very wrong. `helper` is a local variable and is no longer valid as soon as the function exits. Furthermore, function parameters in C are passed by value. So `array` is a local variable and setting it does not change the caller's variable. – kaylum Jan 23 '21 at 10:47
  • 1
    So if I understand correctly, by using helper I changed the variable that my pointer was pointing? – Feanor Nosselo Jan 23 '21 at 10:50
  • Actually this may be better: [Allocate memory 2d array in function C](https://stackoverflow.com/questions/15062718/allocate-memory-2d-array-in-function-c) – kaylum Jan 23 '21 at 10:50

0 Answers0