[
C++
]
Pointers in C/C++
How are various data types stored in computer memory?
Can we operate upon memory addresses in programs?
Pointers are variables that store the address of another variable.
Pointers to Pointer
int p = int **q;
Pointers as Function Arguments - Call by Reference
#include <stdio.h>
void Increment(int a)
{
a = a+1;
}
int main()
{
int a;
a = 10;
Increment(a);
printf("a = %d", a);
}
Using pointers
#include<stdio.h>
void Increment(int *p)
{
*p = (*p) + 1;
}
int main()
{
int a;
a = 10;
Increment(&a);
printf("a = %d", a);
}
Pointers and Array
#include<stdio.h>
int main()
{
int A[] = {2,4,5,8,1};
printf("%d\n", A);
printf("%d\n", &A[0]);
printf("%d\n", A[0]);
printf("%d\n", *A);
}
In most contexts, array names decay to pointers. In simple words, array names are converted to pointers. That’s the reason why you can use pointers to access elements of arrays. However, you should remember that pointers and arrays are not the same.
There are a few cases where array names don’t decay to pointers. To learn more, visit: When does array name doesn’t decay into a pointer?