Tuesday, August 8, 2017

memory allocation and free of 2D array




#include <stdio.h>
#include <stdlib.h>

int main() {
  float **p;
  int m, n, i, j;

  printf("Enter number of rows and columns: ");
  scanf("%d%d", &m, &n);

  /* Allocate memory */
  p = (float *) malloc(sizeof(float *) * m); /* Row pointers */
  for(i = 0; i < m; i++) {
    p[i] = (float) malloc(sizeof(float) * n); /* Rows */
  }

  /* Assign values to array elements and print them */
  for(i = 0; i < m; i++) {
    for(j = 0; j < n; j++) {
      p[i][j] = (i * 10) + (j + 1);
      printf("%6.2f ", p[i][j]);
    }
    printf("\n");
  }

  /* Deallocate memory */
  for(i = 0; i < m; i++) {
    free(p[i]); /* Rows */
  }
  free(p); /* Row pointers */
}


Ref:http://www.annigeri.in/2011/11/dynamic-two-dimensioned-arrays-in-c.html

Same as above program:

int **array;
array = malloc(nrows * sizeof(int *));
if(array == NULL) {
fprintf(stderr, “out of memory\n”);
/*exit or return*/
for(i = 0; i < nrows; i++) {
array[i] = malloc(ncolumns * sizeof(int));
if(array[i] == NULL) {
fprintf(stderr, “out of memory\n”);
/*exit or return*/
}
}
Ref: http://www.writeulearn.com/memory-allocation-deallocation-2d-array/

same as above:
We can create an array of pointers also dynamically using a double pointer. Once we have an array pointers allocated dynamically, we can dynamically allocate memory and for every row like method 2.
#include <stdio.h>
#include <stdlib.h>
int main()
{
    int r = 3, c = 4, i, j, count;
    int **arr = (int **)malloc(r * sizeof(int *));
    for (i=0; i<r; i++)
         arr[i] = (int *)malloc(c * sizeof(int));
    // Note that arr[i][j] is same as *(*(arr+i)+j)
    count = 0;
    for (i = 0; i <  r; i++)
      for (j = 0; j < c; j++)
         arr[i][j] = ++count;  // OR *(*(arr+i)+j) = ++count
    for (i = 0; i <  r; i++)
      for (j = 0; j < c; j++)
         printf("%d ", arr[i][j]);
   /* Code for further processing and free the
      dynamically allocated memory */
   return 0;
}

No comments:

Post a Comment