Search code examples
cpointersdynamic-memory-allocationpointer-to-pointer

How to use double pointer as pointer arrays?


Version 1:

struct mydef_s1 {
    int argc;
    char *argv[3];
};          

struct mydef_s1   *p1 = (struct mydef_s1*) malloc (sizeof (struct mydef_s1));     
p1->argv[0] = malloc (8);
p1->argv[1] = malloc (16);
p1->argv[2] = malloc (24);

Now, I want to achieve above with the following structure declaration?

Version 2:

struct mydef_s2 {
    int argc;
    char **argv;
};  

If I am right, then following would like allocate just 8 bytes (4 for memory pointer & 4 for integer in my machine)

struct mydef_s2   *p2 = (struct mydef_s2*) malloc (sizeof (struct mydef_s2));

What should I do to do the following?

p2->argv[0]= malloc(4);
p2->argv[1]=malloc(8);

Solution

  • In the case of a pointer to pointer like

    struct mydef_s2 {
        int argc;
        char **argv;
    };  
    

    you have to first allocate the memory for argv itself, then for argv[i]s.

    Something like (code is without error check)

      argv = malloc(n * sizeof*argv);  //allocate memory to hold 'n' number of 'argv[i]'s
      for (i = 0; i < n; i++)
           argv[i] = malloc(32);    //allocate individual `argv[i]`s
    

    will do the job.