POINTERS & ARRAYS
POINTERS & ARRAYS
POINTERS & ARRAYS
value.
The symbol of an address is represented by a pointer. In addition to creating and modifying dynamic data
structures, they allow programs to emulate call-by-reference. One of the principal applications of pointers is
iterating through the components of arrays or other data structures. The pointer variable that refers to the same data
type as the variable you're dealing with has the address of that variable set to it (such as an int or string).
Syntax
datatype *var_name;
int *ptr; // ptr can point to an address which holds int data
Since the data type knows how many bytes the information is held in, we associate it with a reference. The size of
the data type to which a pointer points is added when we increment a pointer.
Advantage of pointer
1) Pointer reduces the code and improves the performance, it is used to retrieving strings, trees etc. and used with
arrays, structures and functions.
3) It makes you able to access any memory location in the computer's memory.
Declaring a pointer
The pointer in C++ language can be declared using ∗ (asterisk symbol).
#include <iostream>
using namespace std;
int main()
{
int number=30;
int ∗p;
p=&number;//stores the address of number variable
cout<<"Address of number variable is:"<<&number<<endl;
cout<<"Address of p variable is:"<<p<<endl;
cout<<"Value of p variable is:"<<*p<<endl;
return 0;
}
Output:
ARRAYS IN C++
In C++ std::array is a container that encapsulates fixed size arrays. In C++, array index
starts from 0. We can store only fixed set of elements in C++ array.
#include <iostream>
using namespace std;
int main()
{
int arr[5]={10, 0, 20, 0, 30}; //creating and initializing array
//traversing array
for (int i = 0; i < 5; i++)
{
cout<<arr[i]<<"\n";
}
}
Output:
10
0
20
0
30
C++ array with empty members
The maximum number of elements that can be stored in an array in C++ is n. What will
happen, though, if we store fewer than n elements?
For example,
int x[6] = {19, 10, 8}; // store only 3 elements in the array
The array x in this case is 6 elements wide. But we've only given it a three-element
initialization.
When that happens, the compiler fills in the empty spaces with random values. This
random value frequently appears as 0.
The address of the subsequent element, x[1], will then be 2124, followed by x[2], 2128, and so forth.
Each element in this case has a four-fold increase in size. This is due to the fact that int has
a 4 byte capacity.