Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 changing length arrays
Index -> Programming, C -> C Help
View previous topic Printable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
Fonzie




PostPosted: 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?
Sponsor
Sponsor
Sponsor
sponsor
Tony




PostPosted: 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.
Latest from compsci.ca/blog: Tony's programming blog. DWITE - a programming contest.
Fonzie




PostPosted: 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.
Tony




PostPosted: 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.
Latest from compsci.ca/blog: Tony's programming blog. DWITE - a programming contest.
Fonzie




PostPosted: Sun Oct 21, 2007 10:42 am   Post subject: Re: changing length arrays

thanks, working now.
Display posts from previous:   
   Index -> Programming, C -> C Help
View previous topic Tell A FriendPrintable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 1 of 1  [ 5 Posts ]
Jump to:   


Style:  
Search: