0

In Java, we sometimes do this:

int [] foo = new int [5]

How do you do this in C++? I've put this in and it gave me an error.

harsh
  • 85
  • 1
  • 3
  • 9
  • There are many ways. For example `std:array foo;` – Michael Apr 27 '14 at 18:44
  • 4
    Of course it gave an error, they're different languages. If you're going to ask this style of question repeatedly, you should invest in a [good C++ book](http://stackoverflow.com/q/388242/395760). Or just hone your ability to search the internet... –  Apr 27 '14 at 18:45
  • @user3554687: if you like one of the answers, could you accept it by clicking on a tick next to the score of the answer - it should become green. – Yulia V Apr 27 '14 at 19:35

3 Answers3

2
std::vector<int> foo(5);

Don't use int[], this is ok if the size of your array is fixed (you do not need new, just

int a[5];

), but if it is variable, than it is a pain because you need to remember to disallocate it.

Yulia V
  • 3,507
  • 10
  • 31
  • 64
  • I suggest std::vector instead of "naked" pointers because user3554687 needs to leart to use std library, it will greatly benefit him. Naked pointers require disallocation, if the size of the array is not fixed (which is generally the case). This is more C than C++. – Yulia V Apr 27 '14 at 18:46
2
int *foo = new int[5];

This is how it is done without using any library, but you will have to manually delete that memory after you are done with it or else you have a memory leak

It is not recommended that you do it that way thought. You should use std::array if the size of the array will not change during its life time. If you want an array that can dynamic grow than you should use std::vector.

Caesar
  • 9,483
  • 8
  • 40
  • 66
1

Use

int foo[5];

or

int *foo = new int[5];
...
delete []foo; // remember to release its memory afterwards!!!

or

#include <vector>
...
std::vector<int> foo(5);
herohuyongtao
  • 49,413
  • 29
  • 133
  • 174