C Pointers
C Pointers
A basic introduction
POINTERS
WHAT IS A POINTER ?
01
Pointers are variables that #include <stdio.h> Here,
store addresses int i is a variable with a
int main() value of 5.
Addresses are memory {
locations. int i = 5; This value is stored at
somewhere in our RAM
Memory locations are int *ptr = &i; (Memory)
where our program stores return 0;
data. } To access it we need an
address.
i 5
ptr 0x003e
This is a pointer ->
f323
look how it’s 0x003ef323 <- This is a memory location
0x003ef500 or simply a address
pointing to address
of int i;
POINTERS
WHAT IS A POINTER ?
01
&(ampersand) is called The A pointer is declared in the
Address Operator . following way :
int *pointer_name;
void *ptr;
Now it can hold any types of data’s addresses. Be it float, int, char etc.
POINTERS
VOID POINTERS
01
But void pointers cannot be dereferenced. They are type-casted.
a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9]
‘H’ ‘E’ ‘L’ ‘O’ ‘W’ ‘O’ ‘R’ ‘L’ ‘D’ ‘\n’
a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9]
‘H’ ‘E’ ‘L’ ‘O’ ‘W’ ‘O’ ‘R’ ‘L’ ‘D’ ‘\n’
return 0;
} x[0] x[1] x[2] x[3] x[4]
1 2 3 4 5
POINTERS
ARRAY AND POINTERS
01
#include <stdio.h> Output :
But, *(ptr-1) is different.
int main() *ptr = 1
{ *(ptr+1) = 2 we can generally assume we’re doing index
int x[5] = {1, 2, 3, 4, 5}; *(ptr-1) = 32767 addition.
int* ptr; &x[0 + 1] = x[1]
ptr = x; but, x[0-1] = x[-1]
printf("*ptr = %d \n", *ptr);
printf("*(ptr+1) = %d \n", *(ptr+1)); there’s no such thing as x[-1] . So we will
printf("*(ptr-1) = %d", *(ptr-1)); either get 0 or a random Garbage value.
return 0;
} x[0] x[1] x[2] x[3] x[4]
1 2 3 4 5