Skip to content

Instantly share code, notes, and snippets.

@alopatindev
Last active January 9, 2016 01:10
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 alopatindev/ee1aaa7b141cde696356 to your computer and use it in GitHub Desktop.
Save alopatindev/ee1aaa7b141cde696356 to your computer and use it in GitHub Desktop.
Passing multidimensional array created on stack as function argument without dimention specifying
// "we can not declare that function as accepting a pointer-to-pointer" (c) https://www.eskimo.com/~scs/cclass/int/sx9a.html
// Instead we can do this ugly thing
#include <stdio.h>
#include <stdlib.h>
void printStackArray(const int* const arr, const size_t n, const size_t m)
{
size_t i, j;
for (i = 0; i < n; i++)
{
for (j = 0; j < m; j++)
{
printf("%02d ", arr[i * m + j]);
}
printf("\n");
}
}
void printHeapArray(const int* const* const arr, const size_t n, const size_t m)
{
size_t i, j;
for (i = 0; i < n; i++)
{
for (j = 0; j < m; j++)
{
printf("%02d ", arr[i][j]);
}
printf("\n");
}
}
void testStackArray(const size_t n, const size_t m)
{
int c = 1;
int a[n][m];
size_t i, j;
for (i = 0; i < n; i++)
{
for (j = 0; j < m; j++)
{
a[i][j] = c;
c++;
}
}
printStackArray((const int* const)a, n, m);
}
void testHeapArray(const size_t n, const size_t m)
{
int c = 1;
int** aa = (int**)malloc(sizeof(int*) * n);
size_t i, j;
for (i = 0; i < n; i++)
{
aa[i] = (int*)malloc(sizeof(int) * m);
for (j = 0; j < m; j++)
{
aa[i][j] = c;
c++;
}
}
printHeapArray((const int* const* const)aa, n, m);
for (i = 0; i < n; i++)
{
free(aa[i]);
}
free(aa);
}
int main()
{
const size_t n = 2;
const size_t m = 3;
testStackArray(n, m);
printf("\n");
testHeapArray(n, m);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment