array stuff

Started by
6 comments, last by hello_there 21 years, 2 months ago
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.
____________________________________________________________How could hell be worse?
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();
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 correctlyif(array) { array[0] = 5; }// Finally don't forget to free the allocated memory// but also only when it is validif(array) { delete [] array; }  


Somebody was faster


[edited by - mrandrew on February 6, 2003 11:58:27 PM]
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]
____________________________________________________________How could hell be worse?
Or use std::vector instead of messing with new and delete.

Helpful links:
How To Ask Questions The Smart Way | Google can help with your question | Search MSDN for help with standard C or Windows functions
what std::vector?
____________________________________________________________How could hell be worse?
quote:what std::vector?


you''ll be asking ''what''s google?'' next.
quote:Original post by mrandrew
if(array) { delete [] array; } 

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


Update GameDev.net system time campaign: ''date ddmmHHMMYYYY''
Arguing on the internet is like running in the Special Olympics: Even if you win, you're still retarded.[How To Ask Questions|STL Programmer's Guide|Bjarne FAQ|C++ FAQ Lite|C++ Reference|MSDN]

This topic is closed to new replies.

Advertisement