C++ Day 6!: Pointers!
HahaYes (1900)

Day 6! of my C++ Tutorial!

Note: I realise that there are now competitors, but please be more nice.

Featured Shoutout: @CodeLongAndPros check out his awesome C Tutorial!


What are pointers?

A pointer in C++(and programming in general) is a object that stores a memory address.
Example of a pointer:

#include <iostream>
using namespace std;

int main () {
   int  var1;
   char var2[10];

   cout << "Address of var1 variable: ";
   cout << &var1 << endl;

   cout << "Address of var2 variable: ";
   cout << &var2 << endl;

   return 0;

(This came from Tutorialspoint)
So again, A pointer is a variable whose value is the address of another variable. Like any variable or constant, you must declare a pointer before you can work with it. The general form of a pointer variable declaration is like this"

type *var-name;

Here, type is the pointer's base type; it must be a valid C++ type and var-name is the name of the pointer variable. The asterisk you used to declare a pointer is the same asterisk that you use for multiplication. However, in this statement the asterisk is being used to designate a variable as a pointer.
Some Pointer declarations: (I just spelled that so wrong someone tell me how to spell it)

int    *ip;    // pointer to an integer
double *dp;    // pointer to a double
float  *fp;    // pointer to a float
char   *ch     // pointer to character

The data type of all these pointers are still those hexadecimal number that show a memory adres.

How to actually use pointers"

#include <iostream>
using namespace std;

int main () {
   int  var = 42;   // actual variable declaration.
   int  *ip;        // pointer variable 

   ip = &var;       // store address of var in pointer variable

   cout << "Value of var variable: ";
   cout << var << endl;

   // print the address stored in ip pointer variable
   cout << "Address stored in ip variable: ";
   cout << ip << endl;

   // access the value at the address available in pointer
   cout << "Value of *ip variable: ";
   cout << *ip << endl;

   return 0;

When you run it, it should show something like this:
The Output:

Value of var variable: 42
Address stored in ip variable: 0x7ffca90a4708
Value of *ip variable: 42

Anyways, it is pretty cool.
I'm sorry that I'm kinda bad at pointers. If anyone wants to help me make it better, please contact me in the comments below.


Please Upvote!

Another featured repliter
@DynamicSquid THanks for all the shoutouts! :)

You are viewing a single comment. View All