Allocating memory to a pointer to an array in another function

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • aspire
    New Member
    • Aug 2009
    • 1

    Allocating memory to a pointer to an array in another function

    All,

    I am trying to allocate memory to a pointer to an array in another function, but i am not getting a successful compilation. I am getting error on a line shown below in code.

    ------------
    #include "stdio.h"
    #include "stdlib.h"

    void store(int (**maxtab)[2])
    {
    int i;

    for (i = 0; i<10;i++)
    {
    *maxtab = (int (*)[2])realloc(*maxta b, (i+1)*sizeof(in t*)*2 );
    *((*maxtab) + i*2) = 10*i; //error line

    }

    }

    void main()
    int i;

    int (*maxtab)[2];

    store(&maxtab);

    for ( i = 0; i<10;i++)
    {
    mexPrintf("%d \n",maxtab[i][0]);

    }

    realloc(maxtab, 0);

    }
  • Savage
    Recognized Expert Top Contributor
    • Feb 2007
    • 1759

    #2
    Originally posted by aspire
    All,

    I am trying to allocate memory to a pointer to an array in another function, but i am not getting a successful compilation. I am getting error on a line shown below in code.

    ------------
    #include "stdio.h"
    #include "stdlib.h"

    void store(int (**maxtab)[2])
    {
    int i;

    for (i = 0; i<10;i++)
    {
    *maxtab = (int (*)[2])realloc(*maxta b, (i+1)*sizeof(in t*)*2 );
    *((*maxtab) + i*2) = 10*i; //error line

    }

    }

    void main()
    int i;

    int (*maxtab)[2];

    store(&maxtab);

    for ( i = 0; i<10;i++)
    {
    mexPrintf("%d \n",maxtab[i][0]);

    }

    realloc(maxtab, 0);

    }
    That line tries to assign an int to an array of two integers,hence the compiler error.Anyway,wh ole code block inside that function for loop is incorrect.What you need to do is to allocate memory for the pointer which will act as array holding each individual pointer to an array.Then inside that loop you need to allocate sufficient memory for every single array of two integers.Don't be shy to use temporary variables and typedefs, they can make your life a whole lot easier.For e.g you could typedef that pointer to array:

    typedef int (*PointerToArra y)[2];

    And don't forget that releasing that memory is done in opposite order then it's allocation.So first goes the for loop which will free all the pointers to arrays,and then you free the pointer itself.

    Comment

    Working...