Pointer in C
Pointer in C
x
int x=10; 10
Pointer syntax :
data_type *var_name;
Example :
int *p; char*p;
Initialization of Pointer variable
Pointer initialization is the process of assigning address of a variable to
pointer variable.
int a =10;
If a pointer of a
int *ptr; // pointer declaration different type is used,
int ptr=&a; // pointer initialization the program may
misinterpret the data
Or at that address, which
will cause errors.
int*ptr=&a; // initialization and declaration together
Rules of Pointer operations
int a = 10;
int *p = &a; // p is assigned the address of a printf("Value of
a: %d\n", *p); // Output: 10
int a = 20;
int *p1 = &a; // p1 points to a
int *p2 = p1; // p2 now points to the same address as p1
printf("Value of a through p2: %d\n", *p2); // Output: 20
A pointer variable can e initialized with NULL or zero value.
type *array_name[size];
Example
#include <stdio.h>
int main()
{
int a = 10, b = 20, c = 30;
int *arr[3]; // Array of 3 pointers to int
#include <stdio.h>
int main() {
int x = 5;
int y = 10;
printf("Before swap: x = %d, y = %d\n", x, y);
swap(&x, &y);
printf("After swap: x = %d, y = %d\n", x, y);
return 0;
}
POINTER AND STRUCTURE
#include <stdio.h>
int main()
{
struct my_structure
{
char name[20];
int number;
int rank;
};
struct my_structure variable = {"Raji", 35,1};
struct my_structure *ptr;
ptr = &variable;
printf("NAME:%s\n", ptr->name);
printf("NAME:%d\n", ptr->number);
printf("NAME:%d\n", ptr->rank);
return 0;}
Self referential structure
struct node i *p
Address of node
{ inside p
int i;
struct node *p;
}:
Linked list
1. Linked Lists
Each node in a linked list contains a pointer to the next node, allowing nodes to be
linked together in a sequence.
Use of pointers in self referential structures