Pointer is a variable that hold memory address of another variable,the variable may be type of int, char ,array,structure , function or any other pointer.
1. Pointer 'p' is storing memory address of a int type variable 'i'
int i=100; int *p=&i;
2. Pointer 'p' is storing memory address of an Array 'array'
int array[20]; int ( *p )[20]=&array;
3. Pointer 'p' is storing memory address of a function 'show()'
void show(char); void (*p)(char)=&show;
3. Pointer 'p' is storing memory address of struct type variable
struct smallcode { int vikas; float satyam; char sangam; }var; struct smallcode *p=&var;
#include<stdio.h> int main() { char arr[]= "Small Code"; char *p=arr; printf("%c",*p); return 0; }
S
A dangling pointer is a pointer that points to a non-existent or invalid memory location. This situation often occurs when memory has been deallocated or freed, but the pointer still points to the memory location previously held by the deallocated memory.
Accessing or manipulating the data through a dangling pointer can lead to unpredictable behavior, such as accessing unrelated data or causing a program to crash.
Dangling pointer issues can arise in situations such as:
#include <stdio.h> #include <stdlib.h> int* createArray(int size) { int *ptr = (int *)malloc(size * sizeof(int)); return ptr; //returning the address of dynamically allocated memory } int main() { int *array = createArray(5); free(array); // deallocate the memory //Accessing the memory after it has been deallocated leads to a dangling pointer. // This can result in undefined behavior. printf("%d\n", array[0]); return 0; }
A void pointer in C is a special type of pointer that can hold the address of any data type. It is a generic pointer type and does not have any specific data type associated with it.
This makes it a versatile tool for handling memory addresses without needing to specify the data type initially.
void *ptr;
Here, ptr is a void pointer that can point to any data type. To use a void pointer, you generally need to explicitly cast it to the appropriate data type before dereferencing it.
#include <stdio.h> int main() { int num = 10; float fnum = 3.14; char letter = 'A'; void *ptr; // Assigning the address of an integer ptr = # printf("Value pointed to by void pointer: %d\n", *(int*)ptr); // Assigning the address of a float ptr = &fnum; printf("Value pointed to by void pointer: %f\n", *(float*)ptr); // Assigning the address of a character ptr = &letter; printf("Value pointed to by void pointer: %c\n", *(char*)ptr); return 0; }