Archived

This topic is now archived and is closed to further replies.

dynamicman

creating non-constant multidementional arrays

Recommended Posts

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

Share this post


Link to post
Share on other sites
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 while


delete [] num;

// Now we can''t use num anymore



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

Share this post


Link to post
Share on other sites
Cool, just learned malloc and free... I also found another way to do dynamic arrays... I wonder if this is correct..

  
//declare somewhere

int num = 5;
CMyClass** var = new CMyClass*[num];

for(int i = 0; i < num; i += 1)
{
var[i] = new CMyClass();
}

//delete somewhere

for(int i = 0; i < num; i += 1)
{
delete var[i];
}


is this correct? Am I deleting it right?

Share this post


Link to post
Share on other sites
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!]

Share this post


Link to post
Share on other sites