understanding simple memory allocation in C++

Learning a programming language is hard enough without having to wrangle your computer into compiling and executing your code. From beginners to experts, the tips here will make life in C++ easier.
Post Reply
darknkreepy3#
Site Admin
Posts: 253
Joined: Tue Oct 27, 2009 9:33 pm

understanding simple memory allocation in C++

Post by darknkreepy3# »

This is an example to show the way memory is used by variables, pointers, and where they are located in a 32bit and 64bit OS (depending on the computer you are compiling this on, etc)...

Code: Select all

#include <cstdlib>
#include <iostream>
#include <string.h>

using namespace std;

int main(int argc, char *argv[])
	{
	/*---------------------------------------------------
	integers
	*/
	int guess=12345;
	int guess2=67890;
	int guess3=10293;
	
	cout << "Integer memory locations\n----------\n";
	//pointers defined by type*, here int*, same type as the variable they point to
	int* pntEx=&guess;
	int* pntEx2=&guess2;
	int* pntEx3=&guess3;
	
	cout << pntEx << " | " << guess << endl;
	cout << pntEx2 << " | " << guess2 << endl;
	cout << pntEx3 << " | " << guess3 << endl;
	
	/*---------------------------------------------------
	strings
	*/
	string message="Hi there";
	string message2="How are you feeling";
	
	cout << "\n\nString memory locations\n----------\n";
	//pointers defined by type*, here string*, same type as the variable they point to
	string* strPntEx=&message;
	string* strPntEx2=&message2;
	
	cout << strPntEx << " | " << message << endl;
	cout << strPntEx2 << " | " << message2 << endl;
	
	/*---------------------------------------------------
	char arrays
	
		chars are denoted with a single character
		enclosed with single quotes (') not double quotes (")

		char arrays use double quotes(")
	*/
	char* nameFirst="Kristoffe";
	char* nameLast="Brodeur";
	
	cout << "\n\nChar memory locations\n----------\n";
	cout << &nameFirst << " | " << nameFirst << endl;
	cout << &nameLast << " | " << nameLast << endl;

	string pauseDummy;
	cout << "Pausing the program with a phony input (cin)\n"
		<< "check with a program the above memory locations\n"
		<< "input:";
	cin >> pauseDummy;
	
	cout << "\n\n";
		
    	system("PAUSE");
    	return EXIT_SUCCESS;
	}
Post Reply