array of integers whose size depends on a variable

heya.

lets say i have an ifstream name input.

the file contains:
4
9 2 6 10

lets say i store 4 in a.

how can i make the size of array a dependant on the integer a?

like that it would compile something like this
input>>a;
int b[a];

^^ this doesnt work.

Please, need reply asap!

use a pointer and the new operator

1
2
3
4
5
6
7

    int*  b = new int[a]; 

     // or as some prefer

     int*	b = (int*) malloc(4*a);


then refer input>>b[index]

hope this was what you needed
Shredded
Hi Shredded

Your two examples will mostly work in this case but I wouldn't say the choice between new or malloc() is a matter of preferences, they are two different beasts:

1) new constructs objects (that in part is reserving some memory), malloc() just reserves a chunk of bytes. Your second example will only work were ints are 32 bits, and, put aside that portability issue, if malloc() is used for other purpose (building a more complex object), the constructor will not be called at all!

2) new will throw an exception if there is not enough memory, malloc() will just return a NULL, so you cannot use the C++ exception handling with malloc(), you will need to test the return values as if you were programming in plain old C (that is a great language as well, but is not C++).

3) As you have to match new/delete and malloc()/free(), freeing an object allocated with malloc() won't call its destructor either and, if this objects has allocated more stuff, you will have a memory leak there (apart of the other problems of not calling the destructor).

Have to be careful with that, and leave C techniques where they belong. You should use always the new operator in C++.

Cheers
Last edited on
thanks for the information, really helped me alot :)

Topic archived. No new replies allowed.