Skip to content

Instantly share code, notes, and snippets.

@haxpor
Created March 22, 2019 00:37
Show Gist options
  • Save haxpor/a1b7983e8b98ca4dd14c0a22d21fefb9 to your computer and use it in GitHub Desktop.
Save haxpor/a1b7983e8b98ca4dd14c0a22d21fefb9 to your computer and use it in GitHub Desktop.
Solution for question asked in reddit /r/c_programming
/// for https://www.reddit.com/r/C_Programming/comments/b3wnhv/need_help_with_creating_pointers_of_a_2d_array_of/?st=JTJ6V0A6&sh=4926d7ec
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main (int argc, char** argv)
{
// 1. Static fixed-size array
char ss[3][4][255];
for (int i=0; i<3; ++i)
{
for (int j=0; j<4; ++j)
{
snprintf(ss[i][j], 255, "-%d-%d-", i, j);
printf("%s ", ss[i][j]);
}
printf("\n");
}
printf("\n\n");
// 2. 2d array
char* arrstrs[3][4];
for (int i=0; i<3; ++i)
{
for (int j=0; j<4; ++j)
{
arrstrs[i][j] = calloc(1, sizeof(char) * 6);
snprintf(arrstrs[i][j], 6, "-%d-%d-", i, j);
printf("%s ", arrstrs[i][j]);
}
printf("\n");
}
// do something with string inside 2d array of string here ...
// free strings
for (int i=0; i<3; ++i)
{
for (int j=0; j<4; ++j)
{
free(arrstrs[i][j]);
arrstrs[i][j] = NULL;
}
}
printf("\n\n");
// 3. single pointer represents 2d array of string as 1d
char* ss2;
ss2 = calloc(1, sizeof(char) * 3 * 4 * 255);
for (int row=0; row<3; ++row)
{
for (int col=0; col<4; ++col)
{
snprintf((ss2 + row*4*255) + col*255, 255, "-%d-%d-", row, col);
printf("%s ", (ss2 + row*4*255) + col*255);
}
printf("\n");
}
// free strings
free(ss2);
ss2 = NULL;
printf("\n\n");
// 4. double pointers for 2d array of string
char** ss3;
ss3 = calloc(1, sizeof(char*) * 3);
for (int row=0; row<3; ++row)
{
*(ss3 + row) = calloc(1, sizeof(char) * 4 * 255);
// set strings
snprintf((*(ss3 + row) + 0), 255, "-%d-%d-", row, 0);
snprintf((*(ss3 + row) + 1*255), 255, "-%d-%d-", row, 1);
snprintf((*(ss3 + row) + 2*255), 255, "-%d-%d-", row, 2);
snprintf((*(ss3 + row) + 3*255), 255, "-%d-%d-", row, 3);
printf("%s %s %s %s\n",
*(ss3 + row),
*(ss3 + row) + 1*255,
*(ss3 + row) + 2*255,
*(ss3 + row) + 3*255);
}
// free strings
for (int row=0; row<3; ++row)
{
free(ss3[row]);
ss3[row] = NULL;
}
free(ss3);
ss3 = NULL;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment