Link to home
Start Free TrialLog in
Avatar of idek1
idek1

asked on

Malloc question

I have a 2 dimensional array: list[][]
I need to allocate a certain amount of space to it, determined by a third variable, space.

The size of the array is only determined at run-time.
How do I say allocate memory to make the array: list[space][13]
where the 13 is always constant.

I have tried defining the array as "char list[1][13]" at the start of the function and then calling realloc, but it doesn't work.

Any ideas?
ASKER CERTIFIED SOLUTION
Avatar of imladris
imladris
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Is there something that you need clarified before you grade the answer?

Avatar of idek1
idek1

ASKER

Apologies for taking so long... my malloc (Borland C++ 3.1/Dos), only has one paramter, which is the size in bytes of whatthe required memory,  so i assume the lina changes to:
list=(char (*)[13])malloc(space);

Yes?
Almost. Sorry, I tend to use calloc. Anyway, given that list is supposed to wind up with max dimensions of space and 13 (i.e. list[space][13]) you would want to malloc as:

list=(char (*)[13])malloc(space*sizeof(char [13]));


Avatar of idek1

ASKER

Just a further query... Now that I have declared a number of these 2d arrays, say list1, list2, list3, list4 and list5... I want to group them in an additional array so that I can access the 2d array using an index, e.g. in a for loop I want to be able to access ListArray[2] which would be an array holding all the 2d arrays, so ListArray[2] refers to list3, etc.

Thanks,
(P.S. I also need to access elements within the 2d arrays using the ListArray, i.e. I need access to say list4[3] using ListArray.

So you need a pointer to a pointer to an array of thirteen characters:

char (**ListArray)[13];

You would then malloc for the number of 2d arrays there are (say lists):

ListArray=(char (**)[13])malloc(lists*sizeof(char (*)[13]));

Then you would have to assign each one:

ListArray[0]=list1;
ListArray[1]=list2;
ListArray[2]=list3;
etc. etc.

Perhaps it would be easier to just have ListArray? And do the list mallocing in a loop (instead of assigning list1 etc. to ListArray).

Avatar of idek1

ASKER

Thank you very much for your help.
I actually ended up using a structure which contained the list pointer and some other information, and I used an array of these structures to hold all the information.  
Nevertheless, your answers very very helpful.

Thank you.