6

I come from a java background and there's something I could do in Java that I need to do in C++, but I'm not sure how to do it.

I need to declare an array, but at the moment I don't know the size. Once I know the size, then I set the size of the array. I java I would just do something like:

int [] array;

then

array = new int[someSize];

How do I do this in C++?

2
  • Do you just not know the size yet or do you know the size only after you read something at runtime? I.e. is the size a compile time constant? There are more easy ways to solve this than to use new or vectors in that case. Commented Oct 3, 2010 at 19:40
  • I see by the answer you accepted that you don't seem to think std::vector will work for you. Why is that? Commented Oct 3, 2010 at 20:03

7 Answers 7

29

you want to use std::vector in most cases.

std::vector<int> array;

array.resize(someSize);

But if you insist on using new, then you have do to a bit more work than you do in Java.

int *array;
array = new int[someSize];

// then, later when you're done with array

delete [] array;

No c++ runtimes come with garbage collection by default, so the delete[] is required to avoid leaking memory. You can get the best of both worlds using a smart pointer type, but really, just use std::vector.

Sign up to request clarification or add additional context in comments.

2 Comments

Pfff. It's surprising SO-izens are as well behaved as we are. +1.
C++'s std::vector has a lot in common with Java's java.util.ArrayList really. (There are differences too, but the similarities are strong.)
16

In C++ you can do:

int *array; // declare a pointer of type int.
array = new int[someSize]; // dynamically allocate memory using new

and once you are done using the memory..de-allocate it using delete as:

delete[]array;

2 Comments

This is correct and insightful, but really, one should encourage the use of std::vector in C++. That's what the container is there for, and appart from the obvious advantages of standard containers playing well with RAII and so forth, under the skin std::vector has this code there inside byte-for-byte. Usually the reasons not to use standard containers have to do with availability of templates, a given non-standard compiler and so on. I won't upvote this answer not because it's wrong but because it hides lots of important, relevant information that you should always by conscious of.
It is very important that you do delete[] array; otherwise you will leak memory and it's dangerous
1

Best way would be for you to use a std::vector. It does all you want and is easy to use and learn. Also, since this is C++, you should use a vector instead of an array. Here is an excellent reason as to why you should use a container class (a vector) instead of an array.

Vectors are dynamic in size and grow as you need them - just what you want.

Comments

1

The exact answer:

char * array = new char[64]; // 64-byte array

// New array
delete[] array;
array = new char[64];

std::vector is a much better choice in most cases, however. It does what you need without the manual delete and new commands.

Comments

1

As others have mentioned, std::vector is generally the way to go. The reason is that vector is very well understood, it's standardized across compilers and platforms, and above all it shields the programmer from the difficulties of manually managing memory. Moreover, vector elements are required to be allocated sequentially (i.e., vector elements A, B, C will appear in continuous memory in the same order as they were pushed into the vector). This should make the vector as cache-friendly as a regular dynamically allocated array.

While the same end result could definitely be accomplished by declaring a pointer to int and manually managing the memory, that would mean extra work:

  1. Every time you need more memory, you must manually allocate it
  2. You must be very careful to delete any previously allocated memory before assigning a new value to the pointer, lest you'll be stuck with huge memory leaks
  3. Unlike std::vector, this approach is not RAII-friendly. Consider the following example:

    void function()
    {
        int* array = new int[32];
        char* somethingElse = new char[10];
        // Do something useful.... No returns here, just one code path.
        delete[] array;
        delete[] somethingElse;
    }
    

It looks safe and sound. But it isn't. What if, upon attempting to allocate 10 bytes for "somethingElse", the system runs out of memory? An exception of type std::bad_alloc will be thrown, which will start unwinding the stack looking for an exception handler, skipping the delete statements at the end of the function. You have a memory leak. That is but one of many reasons to avoid manually managing memory in C++. To remedy this (if you really, really want to), the Boost library provides a bunch of nice RAII wrappers, such as scoped_array and scoped_ptr.

Comments

1

use std::array when size is known at compile time otherwise use std::vector

#include <array>
constexpr int someSize = 10;
std::array<int, someSize> array;

or

#include <vector>
std::vector<int> array;  //size = 0
array.resize(someSize);  //size = someSize

Comments

-1

Declare a pointer:

int * array;

9 Comments

That's not a very helpful suggestion without quite a bit of extra context.
That would be (the start of) the correct answer in C, but in C++ you should only use a pointer if you have a solid reason for not using std::vector or std::deque.
I assume the solid reason for not using java.util.Vector would transfer and become the solid reason for not using std::vector. And I'm trying a simple answer now. Let's see how it goes.
@aib the simple reason for not using java.util.Vector would be the simple reason it's a C++ question. Java is to C++ what dandelions are to semicolons.
@wilhelmtell what? "I come from a java background and there's something I could do in Java that I need to do in C++, but I'm not sure how to do it. ... I [sic] java I would just do something like: ..."
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.