After going thru the last few video lessons you have there antiRTFM (awesome by the way!), I stumbled upon a situation where I had to use the heap, the code I have commented out shows what the compiler doesn't like, see the comments in the swap function below:
- Code: Select all
#include "stdafx.h"
#include <iostream>
#define _CRT_SECURE_DEPRECATE_MEMORY
#include <memory.h>
using namespace std;
void swap(void *vp1, void *vp2, int size);
int main()
{
int z = 8;
int a = 1929;
cout << "before" << endl;
cout << "z " << z << endl;
cout << "a " << a << endl;
swap(&z, &a, sizeof(int)); //swap z with a
cout << "after" << endl;
cout << "z " << z << endl;
cout << "a " << a << endl;
cin.get();
return 0;
}
void swap(void *vp1, void *vp2, int size)
{
// the compiler will display errors saying that it cannot create an array of size zero:
// char temp[size]
// so I replace that with this:
char * temp = new char[size]; // using the heap in this manner allows for the dynamic creation
// of the temp buffer based on size, it will compile with no errors
memcpy(temp, vp1, size); // the memcpy function from memory.h is used to swap the variables
memcpy(vp1, vp2, size);
memcpy(vp2, temp, size);
delete [] temp; temp = 0; // clean up the heap
}
