Pointers in C
Pointers in C
C Pointer
#include<stdio.h>
int main(){
int number=50;
int *p;
p=&number; //stores the address of number variable
printf("Address of p variable is %x \n",p); // p contains the address of the
number
printf("Value of p variable is %d \n",*p);
return 0;
}
Output:
1) Pointer reduces the code and improves the performance, it is used to retrieving
strings, trees, etc. and used with arrays, structures, and functions.
2) We can return multiple values from a function using the pointer.
3) It makes you able to access any memory location in the computer's memory.
• data_type **pname;
• address of a: d268734
• address of a: d268734
• value stored at p: 10
• value stored at pp: 10
• Double pointer
Pointer Arithmetic
#include<stdio.h>
int main(){
int number=50;
int *p;//pointer to int
p=&number; //stores the address of number variable
printf("Address of p variable is %u \n",p);
p=p+1; //p++
printf("After increment: Address of p variable is %u \n",p); // in our case, p will get i
ncremented by 4 bytes.
return 0;
}
• Output:
#include<stdio.h>
int main(){
int number=50;
int *p;//pointer to int
p=&number; //stores the address of number variable
printf("Address of p variable is %u \n",p);
p=p-1; //p
printf("After decrement: Address of p variable is %u \n",p); // in our case, p will get
decremented by 4 bytes.
return 0;
}
• Output:
#include<stdio.h>
int main(){
int number=50;
int *p; //pointer to int
p=&number; //stores the address of number variable
printf("Address of p variable is %u \n",p);
p=p+3; //adding 3 to pointer variable
printf("After adding 3: Address of p variable is %u \n",p);
return 0;
}
• Output:
• Same like addition it will subtract the address and store it another
address.
• Syntax: new_address= current_address - (number * size_of(data type));
Ex:
#include<stdio.h>
int main(){
int number=50;
int *p; //pointer to int
p=&number; //stores the address of number variable
printf("Address of p variable is %u \n",p);
p=p-3; //subtracting 3 to pointer variable
printf("After subtract 3: Address of p variable is %u \n",p);
return 0;
}
• Output: