Jump to content
  • Advertisement
Sign in to follow this  
NSDuo

dynamic memory: now what?

This topic is 3788 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

A while back I created a topic asking how to allocate memory in C/C++ using malloc. At the time I couldn't fully grasp the concept of pointers, but I found a bunch of tutorials that helped me. Then I revisited the dynamic memory problem and learned that too, there was just one problem... I learned how to request memory and how to free it, and thats it... I'm still not sure how to use the newly allocated memory. Does it work like a regular array (where I could reference a particular block of memory with myarray[3];) only dynamic? Or does it work some other way?

Share this post


Link to post
Share on other sites
Advertisement
It works just like that.
You can't use sizeof() on a dynamically allocated array to obtain the number of bytes in the array however.

Share this post


Link to post
Share on other sites
Yes, just a small example:
Say you would like dynamically integer array you could do the following:

create it with:
int* intarray = (int*) malloc(sizeof(int) * DESIRED_ARRAY_LENGTH);

use it with:
intarray[0], intarray[1], ..., intarray[DESIRED_ARRAY_LENGTH - 1]

and don't go over the array length or you will get undefined results.

destroy it with:
free(intarray);


-edit fixed error

[Edited by - Kamos on February 3, 2008 6:25:40 PM]

Share this post


Link to post
Share on other sites
Quote:
Original post by Kamos
destroy it with:
free(&intarray);
I think that should just be:
free(intarray);
Of course if you're coding in C++, you would want to use new and delete instead (or, better yet, a container from the standard library).

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!