Pointers in C/C++ : Introduction

Shubham Agrawal
2 min readMar 1, 2020

I am assuming you know about variables? So you also know that every variable take memory according to compiler. To keep it simple pointers are also variables which have capability to store address of any other variable.

#include <iostream>
using namespace std;
void main()
{
int a = 5; //variable
int *ptr; //pointer declaration
ptr = &a; //assigning address of a variable to a pointer
}

Address-of operator(&)

This operator is very simple, it just give you the starting memory address of a variable.

#include <iostream>
using namespace std;
void main()
{
int a = 5; //variable
cout<< ”Address of variable a = ”<< &a;
}

Address of variable can be only known at run-time. I am assuming my compiler take 4-bytes for an integer. So memory-layout can be explained with help of below table. Where a is consuming 4 bytes of memory(101–104).

Memory Layout(1st Row — Data, 2nd Row — Memory Address, 3rd row-variable name)

Now there is a issue what will address-of(&) operator will return? as a is consuming 4 bytes. As mentioned in first-line, address of operator will return starting address of memory-block. Therefore in this case 101.

Declaring pointers

It is very very simple to declare a pointer, just add a * before it.

int *p; //a pointer of integer type
char *p; //a pointer of character type
float *p; //a pointer of float type

Assigning variable address to a pointer

We already know how to find address of any variable and how to declare pointers. So lets use these.

#include <iostream>
using namespace std;
void main()
{
int a = 5; //variable
int *ptr; //pointer declaration
ptr = &a; //assigning address of a variable to a pointer
}

Dereference operator (*)

This operator is also a simple operator, it gives you the value stored in memory.

#include <iostream>
using namespace std;
void main()
{
int a = 5; //variable
int *ptr; //pointer declaration
ptr = &a; //assigning address of a variable to a pointer
cout << ptr << (*ptr); //output 101 5, refer above memory layout
}

Size of pointers:

Pointer holds an integer value, which means size of pointer is equal to size of an integer. Type of pointer doesn’t matter at all, whether it is a char pointer or a float pointer or a class pointer, size of pointer will always be same as size of an integer.

class MyClass
{
int a, b, c;
char str[100];
};
int main()
{
int a = 5; //variable
int *iPtr; //int pointer
float *fPtr; // float pointer
char *cPtr; //char pointer
double *dPtr; //double pointer
MyClass *objPtr //class pointer
cout << sizeof(a) // output 4
<< sizeof(iPtr) // output 4
<< sizeof(cPtr) // output 4
<< sizeof(cPtr) // output 4
<< sizeof(dPtr) // output 4
<< sizeof(objPtr); // output 4
//size of integer is compiler dependent it can be 8 also

}

--

--