user8581912
user8581912

Reputation:

Is it possible to dynamically allocate 2-D array in c with using calloc() once?

All the solutions I have seen online has calloc() function used twice, is it possible to do with only using it once? The below code is not printing the correct array elements

int **ptr;

//To allocate the memory 
ptr=(int **)calloc(n,sizeof(int)*m);

printf("\nEnter the elments: ");

//To access the memory
for(i=0;i<n;i++)
{  
 for(j=0;j<m;j++)
 {  
  scanf("%d",ptr[i][j]);
 }
}

Upvotes: 0

Views: 197

Answers (2)

alk
alk

Reputation: 70971

If it's just about minimising the number of calls to memory allocation functions you can created such a jagged array like this:

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

int ** alloc_jagged_2d_array_of_int(size_t n, size_t m)
{
  int ** result = NULL;
  size_t t = 0;

  t += n * sizeof *result;
  t += n*m * sizeof **result;

  result = calloc(1, t);
  if (NULL != result)
  {
    for (size_t i = 0; i < n; ++i)
    {
      result[i] = ((int*) (result + n)) + i*m;
    }
  }

  return result;
}

Use it like this:

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

int ** alloc_jagged_2d_array_of_int(size_t, size_t);

int main(void)
{
  int result = EXIT_SUCCESS;

  int ** p = alloc_jagged_2d_array_of_int(2, 3);
  if (NULL == p)
  {
    perror("alloc_jagged_2d_array_of_int() failed");
    result = EXIT_FAILURE;
  }
  else
  {
    for (size_t i = 0; i < 2; ++i)
    {
      for (size_t j = 0; j < 3; ++j)
      {
        p[i][j] = (int) (i*j);
      }
    }
  }

  /* Clean up. */

  free(p);

  return result;
}

Upvotes: 0

David Ranieri
David Ranieri

Reputation: 41036

Since C99 you can use pointers to VLAs (Variable Length Arrays):

int n, m;

scanf("%d %d", &n, &m);

int (*ptr)[m] = malloc(sizeof(int [n][m]));

for (i = 0; i < n; i++)
{  
    for (j = 0; j < m; j++)
    {  
        scanf("%d", &ptr[i][j]); // Notice the address of operator (&) for scanf
    }
}
free(ptr); // Call free only once

Upvotes: 3

Related Questions