By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
444,246 Members | 1,515 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 444,246 IT Pros & Developers. It's quick & easy.

Allocating memory to a pointer to an array in another function

P: 1
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(*maxtab, (i+1)*sizeof(int*)*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);

}
Aug 2 '09 #1
Share this Question
Share on Google+
1 Reply


Savage
Expert 100+
P: 1,764
@aspire
That line tries to assign an int to an array of two integers,hence the compiler error.Anyway,whole 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 (*PointerToArray)[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.
Aug 2 '09 #2

Post your reply

Sign in to post your reply or Sign up for a free account.