1

In C++, is it possible to create a new array during program runtime? Specifically, suppose I have a data member in a class and the name of the variable is array, which is an array of size 10. Suppose during runtime I want a bigger array, can I do this without using pointers? Can I have a method as follows?

int[] expandCapacity(int currentCapacity) {
     int [] arr = new int[currentCapacity*2];
     currentCapacity*=2;
     return arr;
}

Why can't I use this method to expand the current array's capacity by saying:

currentCapacity = 10;
array = expandCapacity (currentCapacity);

If this works, there would be no need to use pointers. I feel like I'm missing something crucial here. I'd appreciate if you could point out what I am missing.

pb2q
  • 58,613
  • 19
  • 146
  • 147
user1210233
  • 2,730
  • 5
  • 24
  • 31
  • 2
    Even containers like `std::vector` use pointers internally. There's no getting around them. – chris Jun 18 '12 at 15:37
  • 1
    Is this just an interlectual exercise or is there a problem you are trying to solve? – Stefan Jun 18 '12 at 15:38
  • 1
    Besides, pointers are also needed in situation different than "handling chucks of memory of unknown size at compile-time". Take into account, for example, polymorphism by sub-type. A function that returns instances of subclasses of T must be return a T*. – akappa Jun 18 '12 at 15:40

2 Answers2

8

No, this is quite impossible.

However, doing it this way yourself is pure insanity. Use std::vector<int> and let your compiler implementer do it all for you.

Puppy
  • 144,682
  • 38
  • 256
  • 465
3

You should an STL container like a vector for example.

If this works, there would be no need to use pointers. I feel like I'm missing something crucial here. I'd appreciate if you could point out what I am missing.

pointers are useful for much more than this. I recommend finding a good c++ tutorial(check the c++ FAQ here for more).

Community
  • 1
  • 1
WeaselFox
  • 7,220
  • 8
  • 44
  • 75
  • I meant pointers would not be needed for this particular use, not completely useless. But I understand where I was wrong. I should've specified. Thanks – user1210233 Jun 19 '12 at 08:06