Sizing a dynamic C ++ array

I use java and php, and now I need to write C ++ code. I find it hard to create a BYTE array with dynamic size. How to achieve this?

int byteSize = shm.getMemorySize();
BYTE byte[44]; // replace 44 by byteSize
+4
source share
7 answers

You should use std::vectorit if you have no particular reason to use arrays. Usually, in the same context, when you used arrays in other languages ​​in C ++, the default choice should be std::vector.

+8
source

Never use a bare pointer, or it is an open door for errors and memory leaks, instead there are several alternatives:

int len = something;
std::vector<char> buffer(len,0);

or c ++ 11 smart pointer

std::unique_ptr<char[]> buffer{ new char[len] };

or C ++ 14 with make_unique

auto buffen = std::make_unique<char[]>(len);
+4
source

, . , , uint8_t BYTE. , GCC.

#include <vector>
#include <cstdint>
...
std::vector<uint8_t> foo;

#include <cstdint>
...
uint8_t* data;
data = new uint8_t[10];
...
delete[] data;
+2

STL std::vector :

#include <vector> // For std::vector
....

int byteSize = shm.getMemorySize();

// Create a vector of 'byteSize' bytes.
std::vector<BYTE> bytes(byteSize);

, [] (, bytes[0], bytes[1],... bytes[i]).

vector destructor , , .

push_back() ( ). vector clear() .
size() .

std::vector, Stephan T. Lavavej.

+2

:

int byteSize = shm.getMemorySize();
BYTE* byte = new BYTE[byteSize];
//Use the byte
delete [] byte;
+1

- new

BYTE* data = new BYTE[byteSize];
data[0] = 0;
delete [] data;

However, this approach in the hands of a beginner can lead to memory corruption , crash, memory leak and all kinds of behaviors that are difficult to find and fix.

It is best to use std::vectorone that is almost safe for the problems encountered by the first approach:

std::vector<BYTE> data;
data.resize(byteSize);
data[0] = 0;
+1
source

Try the following:

#include <vector>
#include <cstdint> 
[CODE] 
std::vector<uint8_t> data;
+1
source

Source: https://habr.com/ru/post/1533955/