C Pointers
- The pointer in C language is a variable, it is also known as locator or indicator that points to an address of a value.
Advantage of pointer
- Pointer reduces the code and improves the performance, it is used to retrieving strings, trees etc. and used with arrays, structures and functions.
- We can return multiple values from function using pointer.
- It makes you able to access any memory location in the computer's memory.
Usage of pointer
- There are many usage of pointers in c language.
1. Dynamic memory allocation
- In c language, we can dynamically allocate memory using malloc() and calloc() functions where pointer is used.
2. Arrays, Functions and Structures
- Pointers in c language are widely used in arrays, functions and structures. It reduces the code and improves the performance.
Symbols used in pointer
Address Of Operator
- The address of operator '&' returns the address of a variable. But, we need to use %u to display the address of a variable.
#include <stdio.h>
#include <conio.h>
void main(){
int number=50;
clrscr();
printf("value of number is %d, address of number is %u",number,&number);
getch();
}
Output
value of number is 50, address of number is fff4
Example of pointer
#include <stdio.h>
int main()
{
int var = 25;
printf("var: %d\n", var);
// Notice the use of & before var
printf("address of var: %p", &var);
return 0;
}
Expected Output
var: 25
address of var: 3677668
#include <stdio.h>
int main()
{
int* pc, c;
c = 22;
printf("Address of c: %p\n", &c);
printf("Value of c: %d\n\n", c); // 22
pc = &c;
printf("Address of pointer pc: %p\n", pc);
printf("Content of pointer pc: %d\n\n", *pc); // 22
c = 11;
printf("Address of pointer pc: %p\n", pc);
printf("Content of pointer pc: %d\n\n", *pc); // 11
*pc = 2;
printf("Address of c: %p\n", &c);
printf("Value of c: %d\n\n", c); // 2
return 0;
}
Expected Output
Address of c: 2686784
Value of c: 22
Address of pointer pc: 2686784
Content of pointer pc: 22
Address of pointer pc: 2686784
Content of pointer pc: 11
Address of c: 2686784
Value of c: 2