Brandon
Brandon

Reputation: 31

Converting C# byte array to C++

I really appreciate this community and all the help it has provided towards my programming problems that I've had in the past.

Now unfortunately, I cannot seem to find an answer to this problem which, at first glance, seems like a no brainer. Please note that I am currently using C++ 6.0.

Here is the code that I am trying to convert from C#:

byte[] Data = new byte[0x200000];
uint Length = (uint)Data.Length;

In C++, I declared the new byte array Data as follows:

BYTE Data[0x200000];
DWORD Length = sizeof(Data) / sizeof(DWORD);

When I run my program, I receive stack overflow errors (go figure). I believe this is because the array is so large (2 MB if I'm not mistaken).

Is there any way to implement this size array in C++ 6.0?

Upvotes: 3

Views: 1291

Answers (2)

gumik
gumik

Reputation: 623

Defining array this way makes in on stack which ends in stack overflow. You can create very big arrays on heap by using pointers. For example:

BYTE *Data = new BYTE[0x200000];

Upvotes: 3

Mehrdad Afshari
Mehrdad Afshari

Reputation: 421968

Currently, you are allocating a lot of memory on the thread's stack, which will cause stack overflow, as stack space is usually limited to a few megabytes. You can create the array on the heap with new (by the way, you are calculating the array length incorrectly):

DWORD length = 0x200000;
BYTE* Data = new BYTE[length];

You might as well use vector<BYTE> instead of a raw array:

vector<BYTE> Data;
int length = Data.size();

Upvotes: 2

Related Questions