creating non-constant multidementional arrays

Started by
4 comments, last by dynamicman 22 years, 5 months ago
For example, this does not work...
    
int num = 5;
CMyClass* var[num];
  
But, this will work
  
CMyClass* var[5];
  
Does anybody know how to create arrays dynamically? I know we are far from VB (visual basic) land but VB has ReDim to create dynamic arrays. Is there such a thing in C++? I'm guessing I would have to write my own memory allocation code with malloc.... Is there an alternative? Edited by - dynamicman on November 4, 2001 2:05:41 AM
Advertisement
Malloc is easy (so is new, the C++ equivelant). Here are some examples:
  int *num;num = (int *) malloc(sizeof(int) * number_we_want);/* Use num for a while */free(num);/* Now we can''t use num anymore */  

  int *num;num = new int[number_we_want];// Use num for a whiledelete [] num;// Now we can''t use num anymore  


[Resist Windows XP''s Invasive Production Activation Technology!]
Cool, just learned malloc and free... I also found another way to do dynamic arrays... I wonder if this is correct..

  //declare somewhereint num = 5;CMyClass** var = new CMyClass*[num];for(int i = 0; i < num; i += 1){    var[i] = new CMyClass();}//delete somewherefor(int i = 0; i < num; i += 1){    delete var[i];}  


is this correct? Am I deleting it right?
Almost. Just add another "delete [] var;" right on the end.

[Resist Windows XP''s Invasive Production Activation Technology!]
int num = 5;
CMyClass* var[num];

THat would work with a C99 compilant compiler.
quote:Original post by Void
int num = 5;
CMyClass var[num];

I think you meant that without the asterisk. I don''t think that that will work in any C++ standards compliant compilers, I think it has only been added to C. If I''m wrong, and it was added to C++ as well, tell me .

[Resist Windows XP''s Invasive Production Activation Technology!]

This topic is closed to new replies.

Advertisement