Pointer in C .
Pointer in C .
Pointer
for Ex:
int x=5;
int *ptr=&x;
In above example, x is a variable which hold 5 numeric value and when memory
address of x is passes to pointer *ptr, then *ptr manipulate the value hold by x
variable.
An array and a pointer are closely related. In fact, an array can be seen as a special
kind of pointer.
int arr[5];
The variable arr represent the memory address of first element i.e. arr[0].
int *ptr=arr;
Then using pointer, we can access the all element of array. *(ptr+0) means array
element of a[0],*(ptr+1) means second array element of a[1],*(ptr+2) means third
array element of a[2]. Similary ,*ptr pointer access all the element of array.
for example:
#include<stdio.h>
int main(){
int i;
int arr[5]= {2,3,4,5,6};
int *ptr=arr;
for(i=0;i<5;i++){
printf("%d\t",*(ptr+i));
}
return 0;
}
output: 2 3 4 5 6
A void pointer in C is a special type of pointer that can hold the address of an
object of any type. It is a generic pointer that does not have any specific type
associated with it. It is declared using the void * type.
For example:
void *ptr;
Since a void pointer does not have a specific type associated with it, we cannot
directly dereference a void pointer or perform pointer arithmetic on it. Before using
a void pointer, it needs to be explicitly cast to the appropriate type.
What is null pointer?
A null pointer is a special value that a pointer variable does not point to a valid
memory address. In other words, a null pointer does not point to any specific
object or memory location.
Null pointers are commonly used to indicate the absence of a valid object or to
initialize a pointer before assigning it a valid memory address. They are
particularly useful in conditional statements and error handling.
In this code, ptr is initialized as a null pointer. It does not point to any valid
memory location.
for example :
#include<stdio.h>
int main(){
if(!NULL){
printf("C programming is easy");
}
else {
printf(" c programming is not easy");
}
return 0;
}
#include<stdio.h>
int sum(int a, int b) {
return a + b;
}
int main() {
int (*sum_ptr)(int, int);
sum_ptr = sum;
// Calling the function through the function pointer
int result = sum_ptr(3, 5); // result will be 8
printf("the result is %d",result);
return 0;
}
int main() {
int arr[50],size;
printf("enter the size of array:");
scanf("%d",&size);
read(arr,size);
printf("Original array: ");
printArray(arr,size);
Sort(arr,size);
printf("Sorted array: ");
printArray(arr, size);
return 0;
}
void read(int *arr,int size){
int i;
printf("enter the element of array:");
for(i=0;i<size;i++){
scanf("%d",arr+i);
}
}
printf("\n");
}
Sort(arr, size);
printf("The second largest element is %d:",arr[size-
2]);
return 0;
}