-6

How can I allocate memory to an array dynamically(2D)?

    int arr[n];

If I need more or less memory, the dynamic allocation will be more suitable.How can i Do it in C?

alk
  • 69,737
  • 10
  • 105
  • 255
Ananthu
  • 75
  • 2
  • 11

2 Answers2

2

Assuming you have the number of rows "r" and the number of columns "c", you can do this:

int **arr;
arr = malloc(r*sizeof(int*));
for(int i=0; i < r; i++)
{
    arr[i] = malloc(c*sizeof(int));
}

this dynamically allocates an array of pointers to integers, and then allocates arrays of integers to each pointer. Don't forget to delete dynamically allocated arrays when you're done, in this case you should delete the integer arrays first and then the pointer array:

for(int i=0; i < r; i++)
{
    free(arr[i]);
}
free(arr);
hassan arafat
  • 657
  • 5
  • 15
  • So this isn't "one" array, but "1 + rows*columns" arrays. – alk Oct 26 '16 at 06:15
  • This is how C works, you cannot dynamically allocate "one 2D array". Because statically allocated 2D arrays (m x n) are actually allocated as a 1D array of length m*n, and then when accessing this array like arr[i][j], it accesses memory position [i*n+j], but since the compiler isn't aware of "n" when the array is dynamically allocated, you can't assign it as one array, if you do you can't access it as arr[i][j] – hassan arafat Oct 26 '16 at 06:29
  • "*you cannot dynamically allocate "one 2D array"*" you can! :-) You might like to have a look at my answer. – alk Oct 26 '16 at 06:35
  • What your example creates is called a "jagged" array, it's scattered, not using one continuous block of memory. – alk Oct 26 '16 at 06:39
  • yes, it's not allocated contiguously in memory, and it's a little wasteful of memory because you have an array of length "r" of pointers that doesn't really store useful data. But this is the easiest way to do it, without changing access code. – hassan arafat Oct 26 '16 at 06:43
1

Define a pointer to an array and allocated as much memory it is defined to point to:

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


#define ROWS (5)
#define COLUMNS (7)


int main(void)
{
  /* Define and initialise the pointer to the array. */
  int (*p)[ROWS][COLUMNS] = malloc(sizeof *p);

  if (NULL == p)
  {
    perror("malloc() failed");
    return EXIT_FAILURE;
  }

  /* Initialize the array's members. */
  {
    size_t r, c;

    for (r = 0; r < ROWS; ++r)
    {
      for (c = 0; c < COLUMNS; ++c)
      {
        (*p)[r][c] = r * c;
      }
    }
  }

  /* Print the array's members' values. */
  {
    size_t r, c;

    for (r = 0; r < ROWS; ++r)
    {
      for (c = 0; c < COLUMNS; ++c)
      {
        printf("array[%zu][%zu] = %d\n", r, c (*p)[r][c]);
      }
    }
  }

  /* Free the array. */

  free(p)

  return EXIT_SUCCESS;
}

If the C implementation in use supports VLAs one alternatively can do:

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


int main(void)
{
  size_t ROWS = 5;
  size_t COLUMNS = 7;

  ...
alk
  • 69,737
  • 10
  • 105
  • 255