C++/CLR

Advertisement


Question
Hey, Joseph, thanks for the answers last time, can you help me with this bunch of questions?
1) What exactly is dynamic memory allocation?
2) Why do you need an extra hat for String object (in an array)?
3) When initializing CLR array, can you just do array<type>^ name = elements; //if so, why do you need array<type>^ name = gcnew array<type>(size);//if not, what is the difference?
4) Here is a CLR program that I can't compile, I understand there is an declared variable called sample, is there a problem with the code?
#include "stdafx.h"
using namespace System;
int main(array<System::String ^> ^args) {
array<double>^ samples = gcnew array<double>(50);

Random^ generator = gcnew Random;

for(int i = 0; i < samples->Length; i++) sample[i] = 100.0*generator->NextDouble();

Console::WriteLine(L"The array contains the following values: ");
for(int i = 0; i < samples->Length; i++) {
Console::Write(L"{0, 10:F2}", samples[i]);
if((i+1) % 5 == 0) Console::WriteLine(); }

double max = 0;
for each(double sample in samples) if(max< sample) max = sample; //is this line wrong?
Console::WriteLine(L"The maximum value in the array is {0:F2}", max);
return0; }

5) what does this means: "all operations that apparently modify string objects always result in new string objects being created." Does this mean that once a string object is changed, it can not be restored? like str = str + 'a';

Thanks so much

Answer
Hi, Angela.  I love that you number your questions.  It makes it so much easier to differentiate the answers. :)

1. Dynamic memory allocation occurs whenever functions like new and malloc are called.  Generally, when you create a variable, you create the variable on the stack, which is temporary memory used by the program.  When you allocate something dynamically, the memory is created instead on the heap, and exists until it is explicitly deleted.

In C++, dynamic memory allocation pretty much always uses the new keyword.  When you allocate a variable dynamically, you actually create a pointer and call new:

   int* pInt = new int;

In this way, the memory for pInt will always stick around until it is explicitly deleted with a corresponding delete call:

   delete pInt;

You can pass the pointer around without fear that the memory will have been obtained for other purposes.  Consider the following code:

   int* pInt1;
   int* pInt2;

   if (true)
   {
       int temporaryInt = 5;
       pInt1 = &temporaryInt;  // BAD BAD BAD!
       pInt2 = new int;
       pInt2 = 8;
   }

   cout << pInt1 << ' ' << pInt2;

In the above code, assigning the pointer pInt1 the address of the variable temporaryInt is very, very bad.  As soon as temporaryInt falls out of scope (at the end of the if block), the memory has been marked as available for use.  You have no idea what may live in the memory pointed to by pInt1.  pInt2, on the other hand, is guaranteed to always have the value 8 until it is overwritten (either on purpose or accidentally -- programmer error can cause memory overflow to overwrite things which should not be overwritten) or deleted.

Always remember that allocating something dynamically means that you create a pointer first, then assign the dynamically allocated data's address to that pointer.  Also, you must allocate the memory before you can use it, so don't just create a pointer to something and expect that you can now manipulate the data is if it were already allocated.

This is a bit of a rough idea of what dynamic memory allocation is, and I suspect you are actually familiar with the concept, but not the terminology.  If I am incorrect and you would like further details on dynamic memory allocation, please, do not hesitate to ask.  I am more than willing to help you out further.

2. I haven't done a whole lot of CLR programming, so I apologize in advance that I can't go into too much detail on questions 2 and 3.  That said, the ^ character indicates a managed pointer, similar to how a * character indicates an unmanaged pointer.  I suspect that you don't actually have to have the extra ^, but that it's just a good idea to allocate an array of string pointers instead of an array of strings.  Probably more a standard practice than a hard rule.

3. Again, I haven't done much CLR programming, so my answer may be a bit off.  I apologize if it is.  Remember, though, that the ^ character indicates a managed pointer.  When creating an array in this manner, you are dynamically allocating the array (see question 1 ;), so you must first allocate the array before you can use it.  I suspect that you could, in fact, initialize an array outright if you didn't dynamically allocate the array itself, something like:

   array<type> name = elements;

I haven't tried this, though, so it may not work.  Just remember that when you're using the ^ character, you're creating pointers, which generally means you're working with dynamic memory and must allocate the item before you can use it.

4. From the looks of it, the only problem is just a typo -- replace sample[i] in your first for loop with samples[i] and see if that clears it up (notice: samples versus sample).  I set up a C++ CLR console app with your code, made that one change, and it all looks fine.  Compiles and runs, no problem.

5. Basically, all this is saying is that when you perform an operation such as the addition operator that you've given as an example, it isn't modifying the original string.  Instead, it's creating a copy of that string and returning that.  It's actually no different than using the addition operator pretty much anywhere else.  Consider the following:

   int x = 5;
   int y = x + 3;

You don't expect that x + 3 will modify x, and indeed, it doesn't.  In the same way, str + 'a' doesn't modify str.  That's why you have to assign the newly created string back to the old string (the "str =" part).  The actual function would declare a new string and set its contents to the concatenated contents of the original string and the added string, then it would return that newly created string.

As always, if I have not sufficiently answered your questions or if I have raised new questions, or even if you just think of something else to ask, feel free to send me a followup or ask a new question here.

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Joseph Moore

Expertise

I've been programming in one form or another since my brother taught me BASIC when I was 6. I've been programing professionally since I was 20, first web development with HTML, JS, DHTML, CSS, etc., then I became a video game developer, writing code in C, C++, C#, SQL, assembly, and various scripting languages. I've even written my own scripting languages, custom designed for the games I was making. I also dabble in Java, PHP, and Perl. I've worked on pretty much every aspect of game development, including graphics, audio, gameplay, tool, UI, input, animation, and physics.

Experience

I've been writing C++ code for 12 years, both on my own in my spare time and professionally.

Organizations
IGDA

Education/Credentials
Bachelor of Science in Game Design and Development, Full Sail University, Winter Park, FL

Awards and Honors
Salutatorian and Advanced Achiever Awards at Full Sail; Independent Games Festival Student Showcase winner, 2004; Featured article on Gamasutra about an experimental game developed in 2004

©2016 About.com. All rights reserved.