Advertisement

C++ Question.

Started by January 24, 2002 07:29 AM
4 comments, last by Locke 23 years, 1 month ago
Hey all, I have a class with a multiple array in it int array[arryx][arrayy] Now, I can read from a file the data for this array fine, so long as the data is arrayx by arrayy. If I read the size of the data beforehand, is tehre anyway to change the size of the structure? Thanks in advance for any help, Brendan.
Brendan ''Locke'' Hennessy"I heard life sucks, so that''s why I don''t have one"
If I get you right then you want to read in the size of
the data at runtime and then store it in memory.

So I think what you wanna do is dynamic memory allocation.

Look up new and delete for C++,
or if you wanna do it C style you could use malloc() and free().

There are also other functions, but these are typically used.

I hope that helped you little!
Advertisement
Worth mentioning that if you need your arrays to change size AFTER they have been declared, it may be worth using vectors or something similar from the C++ standard template library. Otherwise its down to some messing with realloc() which can be nasty...

If not, ignore me and listen to Beast Master ;¬)

[size="1"]
or, if the size of the array changes a lot, look into linked lists. now if the data is only a number or two numbers, linked lists arent worth it, but if its an array of pointers to some data structure, a linked list is the way to go
If you want to do multi-dimensional dynamic arrays, do this:

  int * a;int width, height;a = new int[width*height];//Now, to access at a particular x/y:int GetAt(int x, int y){ return a[(y*width)+x];}  


I don''t think there is any simpler way anyway.

Hope this helps...

---------------

I finally got it all together...
...and then forgot where I put it.
...and a more detailed version (including file streaming):

    class CIntArray2d{public: CIntArray2d() { pData = NULL; nWidth = 0; nHeight = 0; } ~CIntArray2d() { delete [] pData; } void Size(int,int); void Load(FILE *); int operator() (int,int); //Simple access operator.private: int nWidth, nHeight; int * pData;};void CIntArray2d::Size(int width, int height){ if (pData)  delete [] pData; nWidth = width; nHeight = height; pData = new int[width*height];}void CIntArray2d::Load(FILE * file){ fread(&nWidth,1,sizeof(int),file); fread(&nHeight,1,sizeof(int),file); Size(nWidth,nHeight); fread(pData,(nWidth*nHeight),sizeof(int),file);}int CIntArray2d::operator() (int x, int y){ //Does NOT do ANY validity checking return pData[(y*nWidth)+x];}int main(){ FILE * file = fopen("c:\\dummy.tmp"); CIntArray2d testArray; testArray.Load(file); cout << "Value at 5, 5: " << testArray(5,5) << endl; return 0;}  


Hope this helps
EDIT: Added an example of how to use it.

---------------

I finally got it all together...
...and then forgot where I put it.

Edited by - AdmiralBinary on January 25, 2002 1:21:11 AM

This topic is closed to new replies.

Advertisement