C++:Pointers|sizeof() operator

sizeof() operator in C++

The sizeof() is an operator that evaluates the size of data type, constants, variable. It is a compile-time operator as it returns the size of any variable or a constant at the compilation time.

The size, which is calculated by the sizeof() operator, is the amount of RAM occupied in the computer.

Syntax:

sizeof(data_type);

In the above syntax, the data_type can be the data type of the data, variables, constants, unions, structures, or any other user-defined data type.

 /* to display size of datatype and pointer variable */
#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
	int a=10,*ip;
  	char c='A',*cp;
  	float e=10.45f,*fp;
  	double d=34.67,*dp;
	ip=&a; cp=&c; fp=&e;dp=&d;
  	cout<<"size of int "<<sizeof(a)<<" and size of pointer variable "<<sizeof(ip)<<endl;
  	cout<<"size of char "<<sizeof(c)<<" and size of pointer variable "<<sizeof(cp)<<endl;
  	cout<<"size of float "<<sizeof(e)<<" and size of pointer variable "<<sizeof(fp)<<endl;
  	cout<<"size of double "<<sizeof(d)<<" and size of pointer variable "<<sizeof(dp)<<endl;
  	cout<<"size of int "<<sizeof(*ip)<<endl;
  	cout<<"size of char "<<sizeof(*cp)<<endl;
  	cout<<"size of float "<<sizeof(*fp)<<endl;
	cout<<"size of double "<<sizeof(*dp)<<endl;
  	getch();
	return(0);
}

Output:

size of int 4 and size of pointer variable 8
size of char 1 and size of pointer variable 8
size of float 4 and size of pointer variable 8
size of double 8 and size of pointer variable 8
size of int 4
size of char 1
size of float 4
size of double 8

Pointer arithmetic:

Whenever any increment or decrement is performed with pointer variables, increment or decrement is performed with respect to the size of the data type of the pointer variable. Only two arithmetic operations addition and subtraction can be performed with pointers.

If p is a pointer variable and hold an address 100 then

Data type

Size

P++

p–

P=p+2

P=p-2

Int

4

104

96

108

92

Float

4

104

96

108

92

Char

1

101

99

102

98

Double

8

108

92

116

84