Computer Science Canada

changing length arrays

Author:  Fonzie [ Sat Oct 20, 2007 3:31 pm ]
Post subject:  changing length arrays

I'm not too clear on how realloc works. My first impression was that I could use it to resize the number of elements an array could hold, however, upon further reading (along with the fact that my code doesn't work) it seems realloc changes the amount of space an element can hold. So how do I have an array in which I change the number of elements it can hold throughout the program?

Author:  Tony [ Sat Oct 20, 2007 5:57 pm ]
Post subject:  RE:changing length arrays

realloc works the same way malloc does (but you know, it reallocates)

So to allocate enough room for an array of size N, you are going to need size of element * N amount of space.

Author:  Fonzie [ Sat Oct 20, 2007 11:41 pm ]
Post subject:  Re: changing length arrays

and if I don't know the size of the element? Specifically I'm using a typedef'd structure as an element. Is there no realloc version of calloc? Meaning is there a simple way to change the size of an array without worrying about the size of the element entering the array?

In addition, how do I ever know how many elements an array has when I use malloc and realloc? How does saying how much memory it allocates dictate when an element has finished and a new element begins? I'm finding this concept to be very confusing.

Author:  Tony [ Sun Oct 21, 2007 12:09 am ]
Post subject:  RE:changing length arrays

you could use sizeof to figure out the size needed for the element. Alternatively you could have an array of pointers, and store your larger structures elsewhere. The latter would actually be more efficient if you are resizing often. Or at all.

Author:  Fonzie [ Sun Oct 21, 2007 10:42 am ]
Post subject:  Re: changing length arrays

thanks, working now.


: