tags:

views:

185

answers:

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++?

A: 

Declare a pointer:

int * array;
aib
That's not a very helpful suggestion without quite a bit of extra context.
Oli Charlesworth
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`.
wilhelmtell
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
@aib +1 for that comment. :)
Johannes Schaub - litb
@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
@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: ..."
Johannes Schaub - litb
@litb Oy. Forget what I said. Except for the dandelion part. But forget everything else. k.
wilhelmtell
here's a solid reason why i might be unable to use `java.util.Vector` that doesn't transfer to C++. I want an array of ints, just like in the post.
TokenMacGuy
@TokenMac, `std:vector` provides you with a contiguous storage for the elements. In that regard it is no different from a plain array.
Johannes Schaub - litb
what's different is that the class handles memory management for you. This is a difference in software engineering, not compiler emitted code.
TokenMacGuy
+12  A: 

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.

TokenMacGuy
(I'm sure there some reason why my answer was worthy of a downvote, wrong for some apparent reason, but it would really help me if i knew *why*)
TokenMacGuy
Pfff. It's surprising SO-izens are as well behaved as we are. +1.
Potatoswatter
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.)
Donal Fellows
They both exist for the same reason, because manual memory management isn't worth the hassle (especially for structures more complex than arrays, like search trees). The difference is that the c++ language permits `std::vector` to work equally well over collections of any type the language supports, with strong type checking. In java, that's just not possible.
TokenMacGuy
+4  A: 

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;
codaddict
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.
wilhelmtell
A: 

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.

sukhbir
+1  A: 

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.

peachykeen
I'd say all cases.
GMan
GMan: Except for learning the theory, I'd have to agree.
peachykeen
A: 

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.

Martin Törnwall