Home > Blockchain >  Dynamic memory allocation for two-dimensional arrays
Dynamic memory allocation for two-dimensional arrays

Time:11-30

I want to allocate memory for a two-dimensional array (matrix) and write the sums of the diagonals in a separate one-dimensional array. So my code has an array of pointers to pointers,

int N, ** matrix = NULL;
matrix = (int**) malloc(sizeof(int*) * N);

I fill it and then I create an array to store the sums of the diagonals,

int diag = 2 * N - 1;
int *diagonals = NULL;
diagonals = (int*)malloc(sizeof(int) * diag);

but when I want to write a value into an array, something goes wrong, the values just don't get written into the array; I don't know why.

enter image description here

Here is my code:

#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int main() {
    srand(time(NULL));
    int N, ** matrix = NULL;
    printf("Input the number of rows\n");
    scanf_s("%d", &N);
    printf("\n");
    // Memory allocation for the array of pointers to pointers
    
    matrix = (int**) malloc(sizeof(int*) * N);
    if (matrix != NULL)
    {
        for (int i = 0; i < N; i  )
            *(matrix   i) = (int*)malloc(sizeof(int) * N);

        for (int i = 0; i < N; i  )
        {
            for (int j = 0; j < N; j  )
            {
                matrix[i][j] = rand() % 14 - 4;
                printf("%d\t", matrix[i][j]);
            }
            printf("\n");
        }
        printf("\n");

        int diag = 2 * N - 1;
        int *diagonals = NULL;
        diagonals = (int*)malloc(sizeof(int) * diag);

            for (int i = 0; i < N; i  )
            {
                for (int j = 0; j < N; j  )
                {
                    diagonals[i j]  = matrix[i][j];;
            }
        }

            for (int i = 0; i < diag; i  ) {
                printf("diagonals[%d] - %d\n",i, *(diagonals i));
        }

    }
    else
        printf("Not enough memory.. oops..\n");
}

Here is my code:

#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int main() {
    srand(time(NULL));
    int N, ** matrix = NULL;
    printf("Input the number of rows\n");
    scanf_s("%d", &N);
    printf("\n");
    // Memory allocation for the array of pointers to pointers
    
    matrix = (int**) malloc(sizeof(int*) * N);
    if (matrix != NULL)
    {
        for (int i = 0; i < N; i  )
            *(matrix   i) = (int*)malloc(sizeof(int) * N);

        for (int i = 0; i < N; i  )
        {
            for (int j = 0; j < N; j  )
            {
                matrix[i][j] = rand() % 14 - 4;
                printf("%d\t", matrix[i][j]);
            }
            printf("\n");
        }
        printf("\n");

        int diag = 2 * N - 1;
        int *diagonals = NULL;
        diagonals = (int*)malloc(sizeof(int) * diag);

            for (int i = 0; i < N; i  )
            {
                for (int j = 0; j < N; j  )
                {
                    diagonals[i j]  = matrix[i][j];;
            }
        }

            for (int i = 0; i < diag; i  ) {
                printf("diagonals[%d] - %d\n",i, *(diagonals i));
        }

    }
    else
        printf("Not enough memory.. oops..\n");
}

CodePudding user response:

The following loop assumes that each element of diagonals was initialized to zero, but you performed no such initialization. As a result, they are uninitialized and will contain whatever value happens to be sitting in the newly-allocated memory.

diagonals = malloc(sizeof(int) * diag);
for (int i = 0; i < N; i  )
{
    for (int j = 0; j < N; j  )
    {
        diagonals[i j]  = matrix[i][j];;
    }
}

You have several options for zero-initialization:

  1. Use memset to zero the memory, after allocation:

     diagonals = malloc(sizeof(int) * diag);
     memset(diagonals, 0, sizeof(int) * diag);
    
  2. Initialize values in a loop:

     diagonals = malloc(sizeof(int) * diag);
     for (int i = 0; i < diag; i  ) diagonals[i] = 0;
    
  3. Allocate with calloc:

     diagonals = calloc(diag, sizeof(int));
    

Note that in all cases, you should be checking the result of allocation. If it fails and returns NULL, you should not attempt to access memory via that pointer.

CodePudding user response:

The content of diagonals is allocated with malloc() which does not initialize the memory. You should use calloc() which initializes the memory with zeros:

diagonals = calloc(diag, sizeof *diagonals);

CodePudding user response:

It does not answer the question but I would suggest using real 2D arrays instead of arrays of pointers. To dynamically allocate the 2D array you need to use a pointer to array.

    int (*matrix)[N] = malloc(N * sizeof(*matrix)); 

You will have only one allocation and one free. Fever levels of indirection.

  •  Tags:  
  • c
  • Related