I am used to java and php and now I need to write some c++ code. I got difficulties to create a BYTE-array with dynamic size. How to achieve this?
int byteSize = shm.getMemorySize();
BYTE byte[44]; // replace 44 by byteSize
You should use std::vector unless you have very specific reason to use arrays. Normally, in the similar context where you were using arrays in other languages in C++ the default choice should be std::vector.
resize() perhaps.Never use a naked pointer or it is open door for bugs and memory leaks, instead, here some 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);
Use a vector, unless you absolutely need to handle memory yourself. Also, this is more of a preference thing, but I prefer to use uint8_t instead of BYTE. Its a bit more compliant as it doesn't depend on GCC.
#include <vector>
#include <cstdint>
...
std::vector<uint8_t> foo;
or
#include <cstdint>
...
uint8_t* data;
data = new uint8_t[10];
...
delete[] data;
You can use the STL standard container class std::vector to have a dynamic resizable array:
#include <vector> // For std::vector
....
int byteSize = shm.getMemorySize();
// Create a vector of 'byteSize' bytes.
std::vector<BYTE> bytes(byteSize);
You can access vector elements using the usual [] syntax (e.g. bytes[0], bytes[1], ...bytes[i]).
vector's destructor will automatically release the memory allocated by the vector, so you don't have to pay attention to freeing memory.
You can use vector's push_back() method to add items at the end of the vector (with automatic resizing).
You can use vector's clear() method to empty it.
And vector's size() method returns the current number of items in the vector.
If you want to learn more about std::vector, you can watch this great introductory video by Stephan T. Lavavej.
One way to do it is to use dynamic memory allocation with new
BYTE* data = new BYTE[byteSize];
data[0] = 0;
delete [] data;
However this approach in the hands of a beginner can lead to memory corruptions, crashes, memory leaks, and all sorts of behaviors that are hard to find and fix.
A better way is to use std::vector that is almost safe against the problems the first approach has:
std::vector<BYTE> data;
data.resize(byteSize);
data[0] = 0;
You can create the dynamic array as follows:
int byteSize = shm.getMemorySize();
BYTE* byte = new BYTE[byteSize];
//Use the byte
delete [] byte;
BYTE byte[byteSize];BYTE?