Pointers in C and C++

If you don’t understand pointers in C/C++ can I suggest running up a text editor+gcc or Visual Studio and just typing some code in. Play around with the code and see what you get. Try making a character pointer instead….e.g. the following code might make things easier to understand.

// Test_Pointers_1.cpp : main project file.
// This simple test program explores the basics of pointers in C++
// Pointers can cause a lot of confusion when learning C and C++ therefore
// I encourage you to change the code around until you understand it fully
//
// by:            Rodders
// created:        17th March 2016

#include "stdafx.h"
#include 

using namespace System;
using namespace std;

int main()
{
    int myVariable1 = 25;
    int myVariable2 = 44;

    int ValueHeld;

    int* myPointer;
    char Keyboard;

    Console::WriteLine(L"A Simple Program to Demonstrate Pointers in C++\n\n");

    cout << "The value held by myVariable1 is: " << myVariable1 << " which is held in 
          location: " << &myVariable1 << endl;
    cout << "The value held by myVariable2 is : " << myVariable2 << " which is held in
          location: " << &myVariable2 << endl;

    myPointer = &myVariable1;

    cout << "myPointer is now set to look at myVariable1" << endl;

    ValueHeld = *myPointer;
    cout << "And it points to a memory location that holds the value: " << ValueHeld  << endl;
    cout << "Where my pointer is: " << myPointer << endl;

    myPointer++;
    ValueHeld = *myPointer;
    cout << "\nIncrementing the pointer makes it point to a memory location that holds the value: " << ValueHeld << endl;
    cout << "Where my pointer is now: " << myPointer << endl;

    cout << "\nTherefore the compiler knew it had to add on 4 bytes to get the next integer pointer even though the code was myPointer++";

    cout << "\nPress return to exit";
    cin.ignore();

    return 0;
}

Which gives:

A Simple Program to Demonstrate Pointers in C++

The value held by myVariable1 is: 25 which is held in location: 0018EE44
The value held by myVariable2 is : 44 which is held in location: 0018EE48
myPointer is now set to look at myVariable1
And it points to a memory location that holds the value: 25
Where my pointer is: 0018EE44

Incrementing the pointer makes it point to a memory location that holds the value: 44
Where my pointer is now: 0018EE48

Therefore the compiler knew it had to add on 4 bytes to get the next integer pointer 
even though the code was myPointer++
Press return to exit
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s