Pointer
Pointer
Topic : Pointer
• The memory address is the location of where the variable is stored on the
computer.
• To access it, use the reference operator (&), and the result will represent
where the variable is stored: By Prof. Radhika Shrimankar
Print memory Address
int main()
{
int c = 12;
printf("%u", &c);
return 0;
}
Note:
• The memory address is in hexadecimal form (0x..). You probably won't get the
same result in your program.
• %p control string prints the argument as a memory address in hexadecimal form.
• %u prints memory address in decimal form.
By Prof. Radhika Shrimankar
Define Pointer
• The pointer is a special type of variable, which points (stores) address of
another variable.
• It provides direct access to memory. Using the pointer variable you can
store the address of another simple variable even you can access/edit
the value of that variable.
• For example, an integer variable holds (or you can say stores) an integer
value or address of a integer variable.
Note :- Each pointer variable takes 2 bytes (in 16 bytes compilers)/ 4 bytes (in 32 bytes
compilers) in the memory
int a;
int *p;
p = &a;
Pointers are essential in implementing dynamic data struct Node { int data; struct Node *next;
Data Structures
structures like linked lists, stacks, queues, and trees. };
By passing references instead of copies of large data Passing arrays or structures to functions is
Reduces Code
structures, pointers reduce overhead and improve more efficient using pointers than copying
Complexity
performance. th
Example :-
int a=5,*p;
p=&a;
printf(“\nValue of a is %d”,*p);
*p=40;
printf(“\nValue of a is %d”,*p);
1. Void pointer
2. Null pointer
3. Dangling pointer
• The address that is assigned to any pointer must have the same data
type as we have specified in the declaration of the pointer.
• So, when we are declaring the float pointer, this float pointer won’t be
able to point to an int variable or any other variable.
• In simpler words, it will only be able to point to the float type variable.
We thus use a pointer to void to overcome this very problem.
• Void pointer is capable of pointing to any data type.
• One can assign the void pointer with any data type’s address, and then
assign the void pointer to any pointer without even performing some
sort of explicit typecasting.
• So, it reduces complications in a code.
return 0;
}
• A null pointer is a pointer that does not point to any valid memory
location.
• It is initialized to NULL and used to indicate that the pointer is not
currently holding a valid address.
• Null means that the pointer is referring to the 0th memory
location.
Application/Uses Example
Uninitialized pointer int *ptr = NULL;
End of data structure struct Node *next = NULL;
Error handling if (ptr == NULL) { ... }
Function argument default printMessage(NULL);
Dynamic memory deallocation free(ptr); ptr = NULL;
Recursive base case if (root == NULL) return;
Polymorphism placeholder (C++) Base *ptr = NULL;
Invalid return signal (e.g., fopen) if (file == NULL) { ... }
int main()
{
int *ptr = NULL; // Null pointer
if (ptr == NULL) {
printf("Pointer is null, no valid memory address assigned.\n");
} else {
printf("Pointer is not null.\n");
}
return 0;
}
int main()
{
int *ptr = (int *)malloc(sizeof(int)); // Dynamically allocated memory
*ptr = 42;
return 0;
}
By Prof. Radhika Shrimankar
Const Pointer
// *ptr = 20; // Error: Cannot modify the value through the pointer
ptr = &b; // Allowed: Pointer can point to another address
printf("Value pointed by ptr: %d\n", *ptr);
return 0;
}
You cannot modify the value pointed to by ptr using the pointer.
You can change the pointer to point to another variable.
By Prof. Radhika Shrimankar
Const Pointer
#include <stdio.h>
void salaryhike(int *sal)
{ *sal = *sal+2000;
Output :-
Salary before function is : 5000
} Salary after function call in main is : 7000
int main()
{
int salary=5000;
printf(“Salary before function is : %d", salary);
salaryhike(&salary);
printf(“Salary after function call in main is : %d", salary);
return 0;
By Prof. Radhika Shrimankar
Second Use :- To return more than one value without return statment
#include <stdio.h>
void swap(int *a,int *b)
{ int c;
c=*a; *a=*b; *b=c;
}
int main() Output :-
{ Before function call in main
int a=5,b=8; First value is 5
printf(“Before function call in main “); Second value is 8
printf(“\nFirst value is %d”,a); After function call in main
printf(“\nSecond value is %d”,b); First value is 8
Second value is 5
swap(&a,&b);
printf(“After function call in main“);
printf(“\nFirst value is %d”,a);
printf(“\nSecond value is %d”,b);
return 0;
}
In this method, it passes the value of the In this method, it passes the address of the
1
variable as an argument. variable as an argument.
In this method, the actual value is not In this method, the actual value is
2
modified. modified.
Both formal and actual parameters have Both formal and actual arguments are at
4
different memory locations. the same memory location.
Syntax :-
Syntax :-
Return type funname(dttype
5 Return type funname(dttype var1,dttype
*ptrvar1,dttype *ptrvar2,…)
var2,…) By Prof. Radhika Shrimankar
Return pointer from function
• We can also return pointer from a function.
• When pointer is returned from a function, it must point to data in
the calling function or global variable.
Syntax :
#include <stdio.h>
int main()
{
int array[]={10, 20, 30, 40, 50};
printf(“%u \t %u”, array, &array[0]);
return 0;
}
Output:
2147478270 2147478270
By Prof. Radhika Shrimankar
Pointer to Array
Declaration of pointer to array
data_type *pointer_variable, array_variable[size];
Initialization of pointer to array
pointer_variable=&array_variable[0];
OR
pointer_variable=array_variable;
Example :-
int a[5],*p;
Initialize pointer with the base address of array
p=a; // p=&a[0];
By Prof. Radhika Shrimankar
Pointer Notation
The sizeof operator returns the size of the allocated In case of a pointer, the sizeof operator returns two
space for arrays. or four or more bytes of storage (machine
dependent).
int main()
{
int arr[][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int m = 3, n = 3;
int main()
{
//function name itself holds the memory address of a function
printf("Address of function hello = %p\n",hello);
return 0;
}
void hello()
{
printf("Hello\n");
}
int main()
{
void (*fptr)();
return 0;
}
}
return 0;
By Prof. Radhika Shrimankar
To copy character array to the character array using
pointer.
int main()
{
char s1[10],s2[10],*p1,*p2;
p1 = s1; • p1 - is a character pointer which
p2 = s2;
printf("\nEnter String 1:");
points the first character of the
gets(s1); string. i.e. &s1[0]
while(*p1!='\0')
{
• Like normal pointer arithmetic, if we
*p2 = * p1; move the p1 by 1 (p1+1) position it
p1++;
p2++; will point the next character.
}
*p2 = '\0';
printf("\nString 2 is:");
puts(s2);
return 0;
}
By Prof. Radhika Shrimankar
To concat two Strings using Pointer.
#include <stdio.h> while(*p1!='\0')
int main() {
*p3 = *p1;
{ p3++;
char str1[10],str2[10],str3[10],*p1,*p2,*p3; p1++;
p1 = str1; }
p2 = str2; while(*p2!='\0')
{
p3 = str3; *p3 = *p2;
printf("Enter String 1:"); p3++;
gets(str1); p2++;
}
printf("\nEnter String2:");
*p3 = '\0';
gets(str2); printf("\nCombine string is:");
puts(str3);
getch();
}
By Prof. Radhika Shrimankar
Output-
where,
int main()
{
int *ptr,size,i;
scanf("%d",&size);
if(ptr != NULL)
{
//let's get input from user and print it
printf("Enter numbers\n");
//printing values
printf("The numbers are\n");
scanf("%d",&n);
ptr = calloc(n,sizeof(int));
if(ptr != NULL)
{
//let's get input from user and print it
printf("Enter numbers\n");
//printing values
printf("The numbers are\n");
return 0;
}
malloc() has high time efficiency. calloc() has low time efficiency.
The memory block allocated by malloc() has a The memory block allocated by calloc() is
garbage value. initialized by zero.
Relloc - To alter the size of allocated memory