Jump to content
  • Advertisement

Archived

This topic is now archived and is closed to further replies.

hello_there

array stuff

This topic is 5668 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

is there anyway to load a number from a file and make an array of that size eg ifstream file("file.txt"); file>>size; int array[size]; file.close(); that doesn''t work but is there something you can that would achive the same thing.

Share this post


Link to post
Share on other sites
Advertisement
You need to use the keywords new and delete.

So, you''d have:

ifstream file("file.txt");

file>>size;

// makes an array of ints that is "size" ints long
int *array = new int[size];

// use the array

// cleans up the memory you allocated
delete [] array;

file.close();

Share this post


Link to post
Share on other sites
This doesn't work, because the number is not static. In this case you should use dynamic memory allocation.


file >> size;

int *array = new int[size];

file.close();

// Now access the elements the same way as static
// but be sure, that array has been allocated correctly
if(array) { array[0] = 5; }

// Finally don't forget to free the allocated memory
// but also only when it is valid
if(array) { delete [] array; }


Somebody was faster


[edited by - mrandrew on February 6, 2003 11:58:27 PM]

Share this post


Link to post
Share on other sites
after you delete it can you reasign it with anouther size eg

ifstream file("file.txt");

file>>size;

file.close();

int *array = new int[size];

delete [] array;

ifstream file2("file2.txt");

file2>>size;

file2.close();

*array = new int[size];



[edited by - hello_there on February 7, 2003 3:02:00 AM]

Share this post


Link to post
Share on other sites
quote:
Original post by mrandrew
if(array) { delete [] array; } 


delete [] array; 
is enough, skip the if.



Update GameDev.net system time campaign: ''date ddmmHHMMYYYY''

Share this post


Link to post
Share on other sites

  • Advertisement
×

Important Information

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

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!