Introduction to Pointers
A variable has two identifications in memory:
- Identifier (name in declaration)
- Memory address in RAM
#include<stdio.h>
void main() {
int x;
x = 10;
printf("value of x is %d", x);
printf("\nAddress of x is %d", &x);
}
👉 A pointer is a special variable used to store the address of another variable.
Pointer Declaration
Syntax:
datatype *identifier;
datatype* id;
Example:
#include<stdio.h>
void main() {
int x = 10;
int *px;
px = &x;
printf("Address of x is %d", px);
printf("\nvalue of x is %d", *px);
printf("\nvalue of x is %d", *(&x));
}
Operators:
- & → address-of operator
- * → value-at operator
Advantages of Pointers
- Alternate way to access data in memory
- Enable dynamic memory allocation
- Allow access to data beyond variable scope
Pointer Datatype
The datatype of a pointer determines what type of variable’s address it can store.
#include<stdio.h>
void main() {
int x = 10;
int *px = &x;
float y = 2.34;
float *py = &y;
printf("Address of x is %d", px);
printf("\nvalue of x is %d", *px);
printf("\n\nAddress of y is %d", py);
printf("\nvalue of y is %.2f", *py);
}
Pointer Arithmetic
Valid operations: ++ or +
*px = *px + 1;→ increments the value stored at the addresspx = px + 1;→ moves pointer to next memory location (based on datatype size)
#include<stdio.h>
void main() {
int x = 10;
int *px = &x;
*px = *px + 1; // (*px)++
printf("Present Address inside px is %d", px);
printf("\nvalue referring by px is %d", *px);
px++; // px = px + 1
printf("\n\nPresent Address inside px is %d", px);
printf("\nvalue referring by px is %d", *px);
}
Pointer to Structure
A pointer variable declared with a structure datatype is called a Pointer to Structure. This pointer can store the address of any variable declared from that structure.
Declaration:
struct <structName> *<Var_Id>;
The members of the structure variable can be accessed by its pointer using the arrow operator (->).
#include <stdio.h>
struct sample {
int x;
float y;
};
int main() {
struct sample s;
struct sample *ps;
ps = &s;
ps->x = 12;
ps->y = 45.36;
printf("x=%d", ps->x);
printf("\ny=%0.2f", ps->y);
return 0;
}
Pointer to Array
A pointer variable can be initialized with the address of the first element of an array.
#include<stdio.h>
void main() {
int a[5] = {2,4,6,8,10};
int *pa;
pa = &a[0];
for(int i=0; i<5; i++) {
printf("%d ", *(pa+i));
}
}
Note: The array name itself acts as an implicit pointer to its first element.
#include<stdio.h>
void main() {
int arr[5] = {2,4,6,8,10};
for(int i=0; i<5; i++) {
printf("%d ", *(arr+i));
}
}