C++ Tutorial: Variable References and Pointers

GFreak45

I didnt slap you, i high 5'd your face.
Reaction score
130
Uses: Variables and Functions and Strings and C-Strings

References:

A variable reference is another variable of the same type which uses the same place in memory, therefore, editing or using either of the variables uses or modifies the same value for both variables. To create a variable of this type the format is like so: <type> & <name> = <variable being referenced>;

Useage Example:
Code:
void increment (int&)
//increment - increases the value of the variable by 1
//@param int& - the variable reference to increase
 
int main ()
{
    for (int x = 0; x < 5; increment(x))
        cout << "x equals " << x << endl; //endl is the same as "\n"
    system("Pause");
    return 0;
}
 
void increment (int & var)
{
    var++;
}

This is extremely useful in many instances, and is actually very easy to debug, if you add the const modifier to the beginning of the argument, the variable can not be modified but there isnt a new value created, saving on memory space. ie:
Code:
const int& a = <some variable>;

This creates a reference that you can not modify, essentially creating a read-only variable that can be passed as an argument or used inside classes (but thats for later).

Pointers:

Pointers are a regular int variable that actually holds some memory address, rather than a normal number, the type modifier for pointers is as follows: <type> * <name> = <some address>;
Example:
Code:
int x = 0;
 
int * ptr = &x;

Now ptr references x. Seeing as ptr holds the address of x and not the actual value of x, we need some way to get the value. We do this with the de-reference operator *, like so:
Code:
*ptr = 3;
which actually returns a reference to x.

Recap: (because this is a confusing subject)
Code:
int x = 0; //x equals 0
 
int * ptr = &x; //ptr references the address of x
 
*ptr = 3; //x now equals 3
 
ptr = 0; //ptr now does not reference x
 
*ptr = 1; //error (incorrect address)

Dynamic Allocation with Pointers:

A pointer can be set to an address of a currently non-existant variable via dynamic allocation. This is what the key word new is used for. The format is as follows: <type> * <name> = new <type> (<constructor arguments>);
For example:
Code:
string * sptr = new string ("This is a string.");
This calls the same constructor as the normal variable declaration, but instead of having a name for the variable, you only have the pointer referencing it. These are deleted via the delete operator, ie:
Code:
delete sptr;
If these dynamically allocated variables are not deleted it causes memory leaks while the program is open (memory that is used but no longer referenced, so it can not be used in the application again), until the program is closed these leaks will build up and eventually cause a system crash when your computer runs out of ram. That is why it is important to delete them before you set each dynamically allocated pointer to another value, unless it is still referenced somewhere.

Dynamic Allocation of Arrays with Pointers:

Arrays are dynamically allocated almost the exact same as normal variables with a few key diferences. The constructor is called slightly differently, it is actually like so: <type> * <name> = new <type> [<size of array>];
For example:
Code:
int * arrayptr = new int [10];
this creates a dynamically allocated array of size 10. Dynamically allocated arrays reference the indexes the same way normally allocated arrays do:
Code:
arrayptr[x];
OR
*(arrayptr + x);
the second option uses the dereference operator, however, each index is actually the address of the pointer associated with the array plus the index offset (x in this case)

Another difference would be the delete operator, it is actually delete[] for arrays, like so:
Code:
delete[] arrayptr;

The reason for dynamic allocation of arrays is an adjustable size, normal arrays must have a constant size, dynamic allocation of arrays allows for volatile sizes, for instance:
Code:
int* dynamicArray (int);
//dynamicArray - creates a dynamic array
//@param int - the size of the dynamic array
//@return int* - the address of the created array
 
int main ()
{
    int size;
    cin >> size;
    int* ptrarray = dynamicArray(size);
    for (int x = 0; x < size; x++)
    {
        cout << "Enter a number to insert it into the array: ";
        cin >> ptrarray[x];
    }
    for (int x = 0; x < size; x++)
        cout << "The value in index " << x << " of the array is: " << ptrarray[x] << endl;
    delete[] ptrarray;
    system("Pause");
    return 0;
}
 
int* dynamicArray (int size)
{
    return new int [size];
}
 
General chit-chat
Help Users
  • No one is chatting at the moment.

      The Helper Discord

      Members online

      No members online now.

      Affiliates

      Hive Workshop NUON Dome World Editor Tutorials

      Network Sponsors

      Apex Steel Pipe - Buys and sells Steel Pipe.
      Top