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?
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?
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);
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;
...