Skip to content

Instantly share code, notes, and snippets.

@jiangzc
Created April 20, 2020 08:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jiangzc/6e45da60be82252b3e1d654d45291b41 to your computer and use it in GitHub Desktop.
Save jiangzc/6e45da60be82252b3e1d654d45291b41 to your computer and use it in GitHub Desktop.
dynamic allocate memory to 2d or 3d array
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
int **malloc_2d(int row, int col)
{
if (row < 0 || col < 0)
return NULL;
int *array = (int *)malloc(row * col * sizeof(int));
int **p = (int **)malloc(row * sizeof(int *));
if (array == NULL || p == NULL)
return NULL;
int *ptr = array;
for (int i = 0; i < row; i++)
{
p[i] = ptr;
ptr += col;
}
return p;
}
int ***malloc_3d(int a, int b, int c)
{
int *array = (int *)malloc(a * b * c * sizeof(int));
int **pp = (int **)malloc(a * b * sizeof(int *));
int ***p = (int ***)malloc(a * sizeof(int *));
if (array == NULL || p == NULL || pp == NULL)
return NULL;
int *ptr2 = array;
for (int i = 0; i < a * b; i++)
{
pp[i] = ptr2;
ptr2 += c;
}
for (int i = 0; i < a; i++)
{
p[i] = &pp[i * b];
}
return p;
}
int main()
{
// int **array = malloc_2d(3, 4);
// for (size_t i = 0; i < 3; i++)
// {
// for (size_t j = 0; j < 4; j++)
// {
// array[i][j] = i * 10 + j;
// }
// }
// for (size_t i = 0; i < 3; i++)
// {
// for (size_t j = 0; j < 4; j++)
// {
// printf("%d ", array[i][j]);
// }
// printf("\n");
// }
int ***array = malloc_3d(3, 4, 5);
if (array == NULL)
return 0;
for (size_t i = 0; i < 3; i++)
{
for (size_t j = 0; j < 4; j++)
{
for (size_t k = 0; k < 5; k++)
{
array[i][j][k] = i * 100 + j * 10 + k;
}
}
}
for (size_t i = 0; i < 3; i++)
{
for (size_t j = 0; j < 4; j++)
{
for (size_t k = 0; k < 5; k++)
{
printf("%d ", array[i][j][k]);
}
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment