954,496 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

functions for dynamic struct with dynamic data

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 */

   initFoo(bar);
   ...


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);
         ++j;
      }

      ++i;
   }
}


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

foreshadowed
Newbie Poster
12 posts since Oct 2011
Reputation Points: 10
Solved Threads: 0
 

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 */

initFoo(&bar);
gerard4143
Nearly a Posting Maven
2,272 posts since Jan 2008
Reputation Points: 512
Solved Threads: 387
 


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 */
foreshadowed
Newbie Poster
12 posts since Oct 2011
Reputation Points: 10
Solved Threads: 0
 

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.

MonsieurPointer
Junior Poster
125 posts since Jun 2011
Reputation Points: 31
Solved Threads: 12
 

Post: Markdown Syntax: Formatting Help
You