Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ creating arrays

Tags:

c++

arrays

Why can't I do something like this:

int size = menu.size;
int list[size];

Is there anyway around this instead of using a vector? (arrays are faster, so I wanted to use arrays)

thanks

like image 525
Danny Avatar asked Oct 29 '11 18:10

Danny


People also ask

How do you create an array in C?

To create an array, define the data type (like int ) and specify the name of the array followed by square brackets []. To insert values to it, use a comma-separated list, inside curly braces: int myNumbers[] = {25, 50, 75, 100}; We have now created a variable that holds an array of four integers.

What is * array [] in C?

An array in C/C++ or be it in any programming language is a collection of similar data items stored at contiguous memory locations and elements can be accessed randomly using indices of an array.

Does C automatically initialize arrays?

An array may be partially initialized, by providing fewer data items than the size of the array. The remaining array elements will be automatically initialized to zero.

Which type of arrays can be created in C?

Multi dimensional array can be of two dimensional array or three dimensional array or four dimensional array or more... Most popular and commonly used multi dimensional array is two dimensional array. The 2-D arrays are used to store data in the form of table. We also use 2-D arrays to create mathematical matrices.


2 Answers

The size must be known at compile-time, since the compiler needs to know how much stack space will be needed to allocate enough memory for it. (Edit: I stand corrected. In C, variable length arrays can be allocated on the stack. C++ does not allow variable length arrays, however.)

But, you can create arrays on the heap at run-time:

int* list = new int[size];

Just make sure you free the memory when you're done, or you'll get a memory leak:

delete [] list;

Note that it's very easy to accidentally create memory leaks, and a vector is almost for sure easier to use and maintain. Vectors are quite fast (especially if you reserve() them to the right size first), and I strongly recommend using a vector instead of manual memory-management.

In general, it's a good idea to profile your code to find out where the real bottlenecks are than to micro-optimize up front (because the optimizations are not always optimizations).

like image 68
Cameron Avatar answered Sep 29 '22 11:09

Cameron


As other have said, the C++ language designers have chosen not to allow variable length arrays, VLAs, in spite of them being available in C99. However, if you are prepared to do a bit more work yourself, and you are simply desperate to allocate memory on the stack, you can use alloca().

That said, I personally would use std::vector. It is simpler, safer, more maintainable and likely fast enough.

like image 43
David Heffernan Avatar answered Sep 29 '22 11:09

David Heffernan