I learnt to create heap allocation of 2-D char array and initialize it.
Method 1:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char ** arr;
arr = (char **) malloc(2 * sizeof(char *));
arr[0] = (char *) malloc(256 * sizeof(char));
arr[1] = (char *) malloc(256 * sizeof(char));
sprintf(arr[0], "%s", "This is string 1");
sprintf(arr[1], "%s", "This is string 2");
int i;
for(i = 0; i < 2; i++)
{
printf("%s\n", arr[i]);
}
return 0;
}
But I'm trying to learn is to pass the pointer to a function to create a 2-D array, but in vain.
Method 2:
#include <stdio.h>
#include <stdlib.h>
void test(char *** ptr);
int main()
{
char ** arr;
test(&arr);
sprintf(arr[0], "%s", "This is string 1");
sprintf(arr[1], "%s", "This is string 2");
int i;
for(i = 0; i < 2; i++)
{
printf("%s\n", arr[i]);
}
return 0;
}
void test(char *** ptr)
{
**ptr = (char **) calloc(2, sizeof(char *));
*ptr[0] = (char *) malloc(256 * sizeof(char));
*ptr[1] = (char *) malloc(256 * sizeof(char));
}
Something wrong with the way I'm doing it in Method 2. Please help me understand the way of doing heap allocation of 2-D array by passing pointers. Thanks.