Quick C++ Arrays help please

dexvx

Diamond Member
Feb 2, 2000
3,899
0
0
How do you size an array using a variable?

For some reason, I cant get it to size any kind of array using a variable, giving me a compile time error relating to constant integers.

int Array[10]; //works

int size = 10;
int Array[size]; //fails

const int size = 10;
int Array[size] ; //works

int size = 10;
const int mysize = size;
int Array[size]; // fails

This is part of a larger HashTable class, I've finished the more complex algorithms for it, but cant get this simple thing to work.
 

dighn

Lifer
Aug 12, 2001
22,820
4
81
can't be done that way, have to use dynamic allocation

int* array = new int[size];

don't forgot to delete [] array;


 

Derango

Diamond Member
Jan 1, 2002
3,113
1
0
you can't create an array with a variable size, at least that way.

You need to make a new pointer, and then create a new array from the heap and assign its address to the pointer

int* pointer;
pointer = new int[size];

I think that's the syntax...either that or I'm thinking of java for the syntax ;)

EDIT: bah, got beat while I was trying to figure out if it was java was thinking of :)
 

dexvx

Diamond Member
Feb 2, 2000
3,899
0
0
Well the thing is, its an array of a class called Node.

declaration wise:

Node *Hash = Node Array[size];

so I change it to:

Node *Hash = new Node[size];

Compiling.... la la la ... Testing

Thanks, it works.
 

dexvx

Diamond Member
Feb 2, 2000
3,899
0
0
Originally posted by: dighn
don't forget to delete [] Hash when ur done!

Yea... destructor call for this particular class will be a b!tch, as its a Hash Table of a Linked List of a Splay tree (which should be run from the disk). Last time I ran it through a series of large data sets, my computer ran out of memory.

Thanks for your help.
 

glugglug

Diamond Member
Jun 9, 2002
5,340
1
81
There are a few tree based STL classes that probably do exactly what your looking for, and dynamic size is no problem.

You might want to try using <map> or priority_queue<Node>

In order to use those STL classes for sorting you will need to override the < operator
(define a function with this signature): bool operator<(Node& node1,Node& node2);

VC++ includes source for these classes (I think it has to because they are template based), although its not exactly the most readable code in the world with variable names like a, t, etc. and being template based doesn't help the readability any.