Search code examples
carrayspointersmultidimensional-arraydynamic-memory-allocation

Dynamically allocating a 2D array in C


I've been reading around and I've been applying what I've been reading to my code but I am not sure if I am missing something.. the 2d array is suppose to mirror sudoku. I know the problem area is in my arrayMake function. My professor recommended using a cast with the malloc call so: sudoku = (int**)malloc(sudokus*sizeof(int*)); but that did not work for me.

int main(){
    int sudokus;
    int** sudoku;
    sudokus = getUserInfo();
    sudoku = arrayMake(sudokus);
    /*for (int i = 0; i < (SIZE*sudokus), i++;){
        for (int j = 0; j < SIZE, j++;){
            printf("Numbers[%d][%d]:%d", i, j, sudoku[i][j]);
        }
    }*/
    system("pause");
    return 0;
}

int getUserInfo(){
    int sudokus;
    printf("How many Sudokus are you checking today?\n");
    scanf("%d{^\n]\n", &sudokus);

    return sudokus;
}

int** arrayMake(int sudokus){
    int **sudoku;
    int realsize;
    realsize = 9 * sudokus;

    sudoku = malloc(realsize*sizeof(int*));
    if (sudoku == NULL){
        printf("Memory allocation failed");
        return 0;
    }
    for (int i = 0; i < realsize, i++;){
        sudoku[i] = malloc(9 * sizeof(int));

        if (sudoku[i] == NULL){
            printf("Memory allocaiton failed");
            return 0;
                            }

    }

    return sudoku;
}

Solution

  • My professor recommended using a cast with the malloc call so: sudoku = (int**)malloc(sudokus * sizeof(int*)); but that did not work for me.

    To dynamically allocate for 2D array, you usually need to do two steps. Your code is not clear as you include a realsize = 9 * sudokus which doesn't make sense. Anyway, for simplicity, lets assume your sudoku is a 3x3 matrix. You'll need to:

    1. Allocate for the pointer to pointer to int:

      int **sudoku = malloc( 3 * sizeof( int * ) );
      
    2. Allocate for each of the individual pointer to int:

      for( int i = 0; i < 3; i++ )
          sudoku[i] = malloc( 3 * sizeof( int ) );