🔴 Advanced  ·  Lesson 34

Pointer to Pointer

Pointer to Pointer

What is Pointer to Pointer?

A pointer stores the address of a variable. A pointer to pointer stores the address of another pointer.

Basic Idea
int x = 10;
int *p = &x;
int **pp = &p;

Syntax

ExpressionMeaning
xvalue of variable
&xaddress of x
paddress stored in p
*pvalue of x
ppaddress of p
**ppvalue of x

Example

C Language
#include <stdio.h>

int main() {
    int x = 10;
    int *p = &x;
    int **pp = &p;

    printf("x = %d\n", x);
    printf("*p = %d\n", *p);
    printf("**pp = %d\n", **pp);

    **pp = 50;
    printf("Updated x = %d", x);
    return 0;
}
x = 10 *p = 10 **pp = 10 Updated x = 50

Function Use

Double pointers are useful when a function needs to change a pointer itself.

C Language
#include <stdio.h>
#include <stdlib.h>

void allocate(int **p) {
    *p = (int*) malloc(sizeof(int));
    **p = 100;
}

int main() {
    int *ptr = NULL;
    allocate(&ptr);
    printf("Value = %d", *ptr);
    free(ptr);
    return 0;
}

Summary

  • int **pp stores address of int * pointer
  • **pp accesses the final value
  • Useful in dynamic memory allocation
  • Useful for modifying pointer inside function
  • Also used in arrays of strings and command line arguments

Pointer to Pointer क्या है?

Pointer variable किसी normal variable का address store करता है। Pointer to pointer किसी pointer variable का address store करता है।

C Language
int x = 10;
int *p = &x;
int **pp = &p;

Syntax

ExpressionMeaning
xvariable की value
*px की value
ppp का address
**ppx की value

Example

C Language
int x = 10;
int *p = &x;
int **pp = &p;
**pp = 50;
printf("%d", x);   // 50

Function Use

जब function के अंदर pointer को ही change करना हो, तब double pointer useful होता है।

C Language
void allocate(int **p) {
    *p = malloc(sizeof(int));
    **p = 100;
}

सारांश

  • Double pointer pointer का address store करता है
  • **pp final value access करता है
  • Dynamic memory में useful है
  • Function में pointer update करने के लिए use होता है
  • Command line arguments में भी concept आता है
← Back to C Tutorial