0
0
Cprogramming~5 mins

Pointer declaration

Choose your learning style9 modes available
Introduction
Pointers let you store the address of a variable so you can work with the variable's location directly.
When you want to change a variable's value inside a function.
When you need to work with arrays or strings efficiently.
When you want to manage dynamic memory.
When you want to pass large data structures without copying them.
When you need to create complex data structures like linked lists.
Syntax
C
type *pointerName;
The asterisk (*) shows that the variable is a pointer.
The pointer stores the memory address of a variable of the specified type.
Examples
Declares a pointer p that can hold the address of an int variable.
C
int *p;
Declares a pointer cptr that can hold the address of a char variable.
C
char *cptr;
Declares a pointer fptr that can hold the address of a float variable.
C
float *fptr;
Sample Program
This program shows how to declare a pointer, assign it the address of a variable, and access the value through the pointer.
C
#include <stdio.h>

int main() {
    int num = 10;
    int *ptr = &num;  // ptr stores the address of num

    printf("Value of num: %d\n", num);
    printf("Address of num: %p\n", (void*)&num);
    printf("Value stored in ptr (address of num): %p\n", (void*)ptr);
    printf("Value pointed to by ptr: %d\n", *ptr);

    return 0;
}
OutputSuccess
Important Notes
Use the ampersand (&) to get the address of a variable.
Use the asterisk (*) to access the value stored at the pointer's address.
Always initialize pointers before using them to avoid errors.
Summary
Pointers store memory addresses of variables.
Use * to declare a pointer and to access the value it points to.
Use & to get the address of a variable.