Thursday, July 30, 2009

Create dynamic array in C++ class?

I am reading a output file with approximately 50 int variables in it. The numbers are stored usingmy current declaration:





in List.h


int data[MAX_LENGTH];





in List.cpp


data[index]=item





I want to be able to dynamically create the array data (using new int[] and pointers, to satisfy an assignment), but still be able to use it as if it were statically created. I would also like to know how I can make the length of data be the length of the input file plus one. In other words, how can I make the array grow/shrink to match the size of it's information? Be nice, I'm only in my 2nd year of C++

Create dynamic array in C++ class?
Let's get the harsh part out of the way first: what you are doing is C, not C++.





The C++ implementation would be to use std::vector%26lt;%26gt;. That class will do what you are asking: it can be treated like a static array (it does offer range checking though!!) but can be resized and is allocated on the heap so size of your data does not matter.


Basic usage is like this:


#include %26lt;vector%26gt;


std::vector%26lt;int%26gt; myVector;


myVector.push_back(1); // let's put in some data..


myVector.push_back(5);


myVector.push_back(10);


cout %26lt;%26lt; myVector[0]; // let's access the contents


cout %26lt;%26lt; myVector[1]; // let's access the contents


cout %26lt;%26lt; myVector[2]; // let's access the contents





Look at the reserve and resize methods of vector to see how you can dynamically change the size of this structure.





If you really have to use new[] then you can simply create it like this:


int* data= NULL;


data= new int[someSize];


//add and retrieve the data


data[0]= 5;


cout%26lt;%26lt; data[0];


// and then get rid of it later with


delete[] data; data=NULL;





You can't really do dynamic resizing of a new'ed array. Instead you would have to create another array of a different size (smaller or larger) and slowly copy everything over from the previous array. Internally this is what std::vector does for you- which is why using reserve() is a good idea to reduce the number of copies.


Hope that helps.





ETA:


You can not call new[] as part of the declaration in your header file, it has to be in your source file:


mylist.h:


char* someList;


mylist.cpp:


someList= new int[500];
Reply:int main (void) {





float d, s1, s2;





int *my_array;





my_array = new int[50]; //or maybe 'new int[MAX_LENGTH]





my_array[33] = 304;





printf("33rd position contains %d",my_array[33]);





return 0;


}


No comments:

Post a Comment