array stuff
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.
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();
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.
Somebody was faster
[edited by - mrandrew on February 6, 2003 11:58:27 PM]
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]
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]
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
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
quote:Original post by mrandrewif(array) { delete [] array; }
delete [] array;
is enough, skip the if
. Update GameDev.net system time campaign:
''date ddmmHHMMYYYY''
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement