Greetings all; what I'm trying to do is create an array of structs dynamically by using functions for allocation, display, and then freeing memory. I'm *able* to do the process if it's within scope of the foo declaration, but the initFoo function throws an exception. I *think* it's the order of dimensions, but I don't know how to correct it.

struct declaration

typedef struct {
   char** _2darray;
} foo;

the declaration

foo *bar = NULL; /* want to create an array of 5 */


the definition

void initFoo(foo *tmp) {

   /* malloc returns are omitted for space */

   int i=0, j=0;
   tmp = malloc(sizeof(*tmp) * 5);

   while(i < 5) { 

      /* loop through each of the 5 elements */
      /* create 5 strings for each element */

      tmp[i]._2darray = malloc(sizeof(*tmp[i]._2darray) * 5);

      while(j < 5) { 

         /* create space for each string */

         tmp[i]._2darray[j] = malloc(20);
         sprintf(tmp[i]._2darray[j], "testing string %d, line %d", i+1, j+1);


I don't quite get how to properly do this within a function and could use help. Thank you for your time in advance.

5 Years
Discussion Span
Last Post by MonsieurPointer

Try defining your function like so:

void initFoo(foo **tmp)
*tmp = malloc(sizeof(foo) * 5);

and pass the pointer like so

foo *bar = NULL; /* want to create an array of 5 */


Edited by gerard4143: n/a


Thank you for your reply - I sure do appreciate it.

Would this be the correct way to initialize the 2d array? It didn't give an error and the output looked okay, but I'm not sure if it's right.

*tmp = malloc(sizeof(foo) * 5);
   (*tmp)[current_element]._2darray = malloc(sizeof((*tmp)[current_element]._2darray) * 5);
   /* want 5 strings for each element of foo */
      (*tmp)[current_element]._2darray[current_string] = malloc(80);
      /* allocate space for each string */

Not quite. You will need (char **)malloc(sizeof(char *) * 5). I've explicitly casted malloc(..) into (char **) because malloc returns void *. Also, the statement malloc(80) could lead to confusion. I would recommend writing it to (char *)malloc(sizeof(char) * 80) instead.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.