Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ dynamic array size definition

Tags:

c++

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
like image 766
Jochen Avatar asked Mar 28 '14 17:03

Jochen


3 Answers

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.

like image 90
Wojtek Surowka Avatar answered Sep 18 '22 03:09

Wojtek Surowka


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);
like image 33
galop1n Avatar answered Sep 17 '22 03:09

galop1n


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;
like image 35
csnate Avatar answered Sep 21 '22 03:09

csnate