FOC Unit IV: Pointer

 

What is a Pointer?
A pointer is a variable that stores the memory address of another variable.

  • Normal variable → stores value
  • Pointer variable → stores the address of a value.

Declaring a Pointer

Syntax:     data_type *pointer_name;

Example:     int *p; // p is a pointer to an integer

Assigning Address to a Pointer

Use & (address-of operator) to store the address of a variable.

Example

int a = 10; int *p; p = &a; // p stores the address of a

Accessing Value Using Pointer

Use * (dereference operator) to get the value stored at the address held by the pointer.

Example

printf("%d", *p); // prints value of a (10)

Pointer Example Program

#include <stdio.h> int main() { int a = 10; int *p; // pointer declaration p = &a; // store address of a in pointer printf("Value of a: %d\n", a); printf("Address of a: %p\n", &a); printf("Pointer p stores: %p\n", p); printf("Value at pointer p: %d\n", *p); return 0; }

Important Pointer Operators
OperatorMeaning
&Address of a variable
*Value at the address (dereference)

Why Use Pointers?

To access and modify values directly from memory.
For dynamic memory allocation (malloc, calloc).
To pass large arrays or structures to functions efficiently.
Used in data structures (linked list, tree, etc.).

Pointer to Pointer (Basic Concept)

A pointer that stores the address of another pointer.

Example

int a = 5; int *p = &a; int **pp = &p; // pointer to pointer

Pointer and Array Relationship (Basic)

Array name itself acts like a pointer.

Example

int arr[3] = {10, 20, 30}; int *p = arr; printf("%d", *p); // prints 10 printf("%d", *(p+1)); // prints 20

Array of Pointers (Pointer Array)

Definition

An array of pointers is an array where each element is a pointer (not a normal variable).

It is useful to store:

addresses of variables
addresses of strings
dynamic data

Syntax

data_type *array_name[size];

Example: Array of Integer Pointers

int a = 10, b = 20, c = 30; int *ptr[3]; // array of 3 integer pointers ptr[0] = &a; ptr[1] = &b; ptr[2] = &c; printf("%d", *ptr[1]); // prints 20

Example: Array of Strings

char *names[] = {"MITAOE", "Computer", "Engineering"}; printf("%s", names[0]); // prints MITAOE printf("%s", names[2]); // prints Engineering

Post a Comment

0 Comments