• C++ Data Types
  • C++ Input/Output
  • C++ Pointers
  • C++ Interview Questions
  • C++ Programs
  • C++ Cheatsheet
  • C++ Projects
  • C++ Exception Handling
  • C++ Memory Management

Related Articles

  • Solve Coding Problems
  • C++ Pointer Operators
  • Function Pointer in C++
  • C++ Modify Pointers
  • C++ Function Call By Pointer
  • Passing Pointers to Functions In C++
  • C++ Functions - Pass By Reference
  • C++ Return 2D Array From Function
  • Erase Range of Elements From List Using Iterators in C++ STL
  • How to Measure Elapsed Time in C++?
  • How to Clear Console in C++?
  • C++ printf() Function
  • How to Get a Unique Identifier For Object in C++?
  • C++ Dereferencing
  • How to Read and Parse Json File with RapidJson?
  • C++ Wait for User Input
  • Create Processes with Fork in C++
  • Pointers in Containers in C++ STL
  • Generate Random Double Numbers in C++
  • C++ Increment and Decrement Operators

C++ Pointer To Pointer (Double Pointer)

In C++ a Pointer is a variable that is used to store the memory address of other variables. It is a  variable that points to a data type (like int or string) of the same type and is created with the * operator.

Syntax of a Pointer in C++:

data_type_of_pointer *name_of_variable = & normal_variable;

What is a Pointer to a Pointer or Double Pointer in C++?

Now, we already know that a pointer stores the memory address of other variables. So, when we define a pointer to a pointer, the first pointer is used to store the address of the variables, and the second pointer stores the address of the first pointer. For this very reason, this is known as a Double Pointer or Pointer to Pointer .

The below diagram explains the concept of Double Pointers : 

Double Pointer

The above diagram shows the memory representation of a Pointer to Pointer or a Double Pointer, we can easily understand that the address of the variable (i.e Address 1) is stored in Pointer 1 and the address of Pointer 1(i.e Address 2) is stored in Pointer 2 . This is known as Double Pointers or Pointer to Pointer .

How to Declare a Pointer to a Pointer in C ++?

Declaring a Pointer to Pointer is similar to declaring a pointer in C++. The difference is we have to use an additional * operator before the name of a Pointer in C++.

Syntax of a Pointer to Pointer(Double Pointer) in C++:

data_type_of_pointer **name_of_variable = & normal_pointer_variable;
int val = 169; int *ptr = &val; // storing address of val to pointer ptr. int **double_ptr = &ptr; // pointer to a pointer declared which is pointing to an integer.

The below diagram explains the concept of Double Pointers: 

How does Double Pointer works?

The above diagram shows the memory representation of a pointer to a pointer. The first pointer ptr1 stores the address of the variable and the second pointer ptr2 stores the address of the first pointer. 

Example: How does Double Pointer works?

Below is the C++ Program to implement Pointer to Pointer :

What will be the size of a pointer to a pointer in C++?

In the C++ programming language double pointer behave similarly to a normal pointer. So, the size of the variable of the double-pointer and the size of the normal pointer variable is always equal.

Below is a C++ program to check the size of a double pointer:

Note: The output of the above code also depends on the type of machine which is being used. The size of a pointer is not fixed in the C++ programming language and it totally depends on other factors like CPU architecture and OS used. Usually, for a 64-bit Operating System, a size of 8 bytes memory and for a 32-bit Operating system, a size of 4 bytes memory is assigned.

Time complexity: O(1). Auxiliary space: O(1).

Please Login to comment...

author

  • cpp-pointer
  • Technical Scripter 2022
  • Technical Scripter
  • pankajdoodhwal0084395

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

  • Utility Programs

MYCPLUS - C and C++ Programming Resources

  • C Tutorials
  • C++ Tutorials
  • Source Code
  • Mobile Tech

Select Page

  • A Complete Guide to using Double Pointer in C: Pointer-to-Pointer

Posted by M. Saqib | Updated Feb 11, 2024 | C Programming: Different Articles on C Programming |

A Complete Guide to using Double Pointer in C: Pointer-to-Pointer

In C programming, a double pointer is a pointer that points to another pointer. It is also referred to as a pointer-to-pointer . A pointer in C is a variable that represents the location of an item, such as a variable or an array. We use pointers to pass information back and forth between a function and its reference point.

Sometimes, a pointer can be declared to point to another pointer which points to a variable. Here, the first pointer contains the address of the second pointer. The second pointer points to an actual memory location where the data is stored, i.e. a variable. That’s the reason why we also call such pointers as double pointers.

Table of Contents

How to declare a pointer-to-pointer, how to initialize a double pointer, c program to show how double pointer works, use double pointer to create two dimensional array, uses of pointer-to-pointer (double pointer), c programming language, 2nd edition, 21st century c: c tips from the new school, c programming absolute beginner’s guide, c programming: a modern approach, 2nd edition, programming arduino: getting started with sketches.

The syntax to declare a double pointer in C is:

In this example, the variable doubleptr is a double pointer to an integer value. The ** notation is used to indicate that doubleptr is a pointer to a pointer. To initialize a double pointer , you can use the address of operator & on a pointer variable, like this:

The following C program shows how pointer-to-pointer works by printing the pointer address as well as variable address and values:

The output of the above C Program is:

Value of var = 120 Value of var pointer = 120 Value of double pointer = 120 Address of var = 0x7ffe25192bfc Address of var pointer = 0x7ffe25192c00 Value in var pointer = 0x7ffe25192bfc Address of double pointer = 0x7ffe25192bfc Value in double pointer = 0x7ffe25192c00

Here is an example that demonstrates how to use double pointers to create a dynamic two-dimensional array. This program demonstrates how double pointers can be used to create complex data structures with dynamic memory allocation in C programming.

This program prompts the user to enter the number of rows and columns for a matrix (two dimensional array), then dynamically allocates memory for the matrix using double pointers. It fills the matrix with values, prints it to the console, and then frees the memory.

Double pointers serve a variety of purposes in C Programming. Here are some of the most common uses of double pointers and why you might want to use them:

  • Dynamic Memory Allocation: Double pointers are often used to allocate memory for arrays, particularly multi-dimensional arrays. By using a double pointer, you can ensure that the memory allocation is protected even outside of a function call. To allocate space for a matrix or multi-dimensional arrays dynamically, you will need a double-pointer.
  • Passing Handles Between Functions: This is particularly useful if you need to pass re-locatable memory between functions.
  • Characters List: Another use is that if you want to have a list of characters (a word), you can use char *word, for a list of words (a sentence), you can use char **sentence, and for list of sentences (a paragraph), you can use char ***paragraph.
  • Main Function Parameters: One of the most common uses (every C programmer should have encountered) as parameters to the main() function , i.e. int main(int argc, char **argv). Here argv is the array of arguments passed on to this program.
  • Linked Lists: Double pointers are frequently used in linked list operations, such as insertion and deletion.

If you’re interested in learning more about double pointers, there are many helpful resources available online. You might start by reading some of the articles on StackOverflow or Quora .

Common Errors with Double Pointers in C

Here are some common errors with double pointers that new programmers make while write C Programming code:

  • Incorrect Syntax: One common mistake when working with double pointers is using the wrong syntax. This can result in compilation errors or unexpected behavior in the program. For example, forgetting to include the ‘*’ operator when dereferencing a double pointer can cause the program to crash.
  • Dereferencing Errors: Another common error is dereferencing incorrectly. This can happen when trying to access memory that hasn’t been allocated or has already been freed. Forgetting to check for NULL values can also lead to segmentation faults.
  • Memory Allocation Errors: Double pointers are often used for dynamic memory allocation in C programming , but errors can occur when allocating memory. Common mistakes include not allocating enough memory, allocating too much memory, or failing to free memory when it’s no longer needed.
  • Type Mismatch Errors: Double pointers can also cause type mismatch errors if they’re not properly cast to the correct type. This can happen when passing double pointers to functions or when assigning values to double pointers.
  • Pointer Arithmetic Errors: Pointer arithmetic can be tricky in C programming, especially when working with double pointers. Common errors include using incorrect operators or not correctly accounting for the size of the data type.

By avoiding these common errors with double pointers in C programming, you can write better C programs. This will also help to improve your overall understanding of double pointers and enhance your programming skills further.

Here’s Must-Read List of C programming books for beginners

C Programming Language

With over 600 5-star reviews on Amazon, readers agree that  C Programming Language, 2nd Edition  by Brian Kernighan and Dennis Ritchie is the best C Programming book for Beginners. The authors present the complete guide to ANSI standard C language programming. Written by the developers of C, this new version helps readers keep up with the finalized ANSI standard for C while showing how to take advantage of C’s rich set of operators, economy of expression, improved control flow, and data structures.

21st Century C

Throw out your old ideas about C and get to know a programming language that’s substantially outgrown its origins. With this revised edition of 21st Century C, you’ll discover up-to-date techniques missing from other C tutorials, whether you’re new to the language or just getting reacquainted.

C Programming Absolute Beginners Guide

Greg Perry is the author of over 75 computer books and known for bringing programming topics down to the beginner’s level. His book  C Programming Absolute Beginner’s Guide , is today’s best beginner’s guide to writing C programs–and to learning skills to use with practically any language. Its simple, practical instructions will help you start creating useful, reliable C code, from games to mobile apps. Plus, it’s fully updated for the new C11 standard and today’s free, open source tools!

C Programming - A Modern Approach

KN King tackles on some C standard library specifics header by header in his  C Programming: A Modern Approach  book. The second edition maintains all the book’s popular features and brings it up to date with coverage of the C99 standard. The new edition also adds a significant number of exercises and longer programming projects, and includes extensive revisions and updates.

Programming Arduino

Simon Monk, a Ph.D. in software engineering, writes this  great little book  for learning to program the arduino using C language. This bestselling guide explains how to write well-crafted sketches using Arduino’s modified C language. You will learn how to configure hardware and software, develop your own sketches, work with built-in and custom Arduino libraries, and explore the Internet of Things—all with no prior programming experience required!

About The Author

M. Saqib

Saqib is Master-level Senior Software Engineer with over 14 years of experience in designing and developing large-scale software and web applications. He has more than eight years experience of leading software development teams. Saqib provides consultancy to develop software systems and web services for Fortune 500 companies. He has hands-on experience in C/C++ Java, JavaScript, PHP and .NET Technologies. Saqib owns and write contents on mycplus.com since 2004.

Related Posts

Conditional Statements – Decision Statements – if, else

Conditional Statements – Decision Statements – if, else

Updated Feb 12, 2024

Structure in C Programming

  • Structure in C Programming

Updated Feb 11, 2024

256-Color VGA Programming in C

  • 256-Color VGA Programming in C

Control Flow in C Programming – The for and while Loop

  • Control Flow in C Programming – The for and while Loop
  • Operators in C Programming
  • Pure Virtual Functions in C++
  • Understanding the Basics of C++ Programming
  • What are the Best C++ Compilers to use in 2024?
  • Rock, Paper, Scissors Game in C++ [C++ Game]
  • C++ Code – Wave File Converter from Text File
  • LRU and FIFO L1 Cache Implementation using C
  • Vigenere Encryption and Decryption in C++
  • Difference between char[] and char* in C? Character Array and Pointer
  • What are #ifndef and #define Directives?
  • Random Number Generation in C/C++: Tricks for Generating, Seeding, and Working with Random Numbers
  • C++ Standard Template Library – List
  • C++ Vectors – std::vector – Containers Library
  • C++ Program to Solve the Quadratic Equation
  • C Algorithms Library
  • Ternary Operator with examples in C
  • C++ “Hello World” Program
  • The “Hello, World!” Program in C
  • File Handling in C++
  • Ternary Operator with examples in C++
  • Polymorphism in C++
  • The C++ Modulus Operator [mod/percentage operator]
  • C Implementation of Base64 Encoding and Decoding
  • Kruskal’s Algorithm Implementation in C
  • Porter’s Algorithm in C
  • Introduction to C++ – Lecture Notes
  • Add time using structures in C++
  • An Introduction to C++
  • Concurrency in C++ – A Course offered by University of Waterloo
  • Common Text Transformation Library
  • Counting Words, Lines and Characters in a Text File in C
  • C Program of Library Management System
  • C Program to Calculate Factorial of a Number
  • C Program to demonstrate 8Queen with simple graphics
  • C++ program to demonstrate Inheritance
  • Union in C Programming
  • Basic Data Types in C Programming
  • C++ Program to demonstrate Function Name Overloading
  • Snake Game – C Imlementation
  • C Program: Number Shuffling Game
  • C Program – Tic-Tac-Toe Game – Command Line
  • Advanced C++ Inheritance Techniques for Effective Object-Oriented Programming
  • Inheritance in C++
  • C++ Memory Management
  • How to Paint in DoS Mode in C [Command Line]
  • C Program to show Fibonacci Sequence

IncludeHelp_logo

  • Data Structure
  • Coding Problems
  • C Interview Programs
  • C++ Aptitude
  • Java Aptitude
  • C# Aptitude
  • PHP Aptitude
  • Linux Aptitude
  • DBMS Aptitude
  • Networking Aptitude
  • AI Aptitude
  • MIS Executive
  • Web Technologie MCQs
  • CS Subjects MCQs
  • Databases MCQs
  • Programming MCQs
  • Testing Software MCQs
  • Digital Mktg Subjects MCQs
  • Cloud Computing S/W MCQs
  • Engineering Subjects MCQs
  • Commerce MCQs
  • More MCQs...
  • Machine Learning/AI
  • Operating System
  • Computer Network
  • Software Engineering
  • Discrete Mathematics
  • Digital Electronics
  • Data Mining
  • Embedded Systems
  • Cryptography
  • CS Fundamental
  • More Tutorials...
  • 📚Tech Articles
  • 🤩Full Forms
  • ☕Code Examples
  • 📰Guest Post
  • ⌨Programmer's Calculator
  • 🥰XML Sitemap Generator
  • 🥰Tools & Generators

IncludeHelp

Home » C programs » C pointer programs

C program to demonstrate example of double pointer (pointer to pointer)

In this C program, we are going to learn about double pointers (pointer to pointer) in C programming language , here we will learn how to declare, assign and use a double pointer (pointer to pointer) in C? Submitted by IncludeHelp , on April 26, 2018

In this program, we have to declare, assign and access a double pointer (pointer to pointer) in C.

As we know that, pointers are the special type of variables that are used to store the address of another variable.

But , when we need to store the address of a pointer variable, we cannot assign it in a pointer variable. To store address of a pointer variable, we use a double pointer which is also known as pointer to pointer .

In this C program, we will understand how to declare, assign and access a double pointer (pointer to pointer)?

C program for double pointer (pointer to pointer)

C Pointer Programs »

Related Programs

  • C program to create, initialize, assign and access a pointer variable
  • C program to swap two numbers using pointers
  • C program to change the value of constant integer using pointers
  • C program to print a string using pointer
  • C program to count vowels and consonants in a string using pointer
  • C program to read array elements and print with addresses
  • C program to read and print student details using structure pointer, demonstrate example of structure with pointer
  • C program to print size of different types of pointer variables
  • C program to demonstrate example of array of pointers
  • An Example of Null pointer in C
  • Making a valid pointer as NULL pointer in C
  • Modify value stored in other variable using pointer in C

Comments and Discussions!

Load comments ↻

  • Marketing MCQs
  • Blockchain MCQs
  • Artificial Intelligence MCQs
  • Data Analytics & Visualization MCQs
  • Python MCQs
  • C++ Programs
  • Python Programs
  • Java Programs
  • D.S. Programs
  • Golang Programs
  • C# Programs
  • JavaScript Examples
  • jQuery Examples
  • CSS Examples
  • C++ Tutorial
  • Python Tutorial
  • ML/AI Tutorial
  • MIS Tutorial
  • Software Engineering Tutorial
  • Scala Tutorial
  • Privacy policy
  • Certificates
  • Content Writers of the Month

Copyright © 2024 www.includehelp.com. All rights reserved.

C – Pointer to Pointer (Double Pointer)

C++ Course: Learn the Essentials

Similar to how a pointer variable in C can be used to access or modify the value of a variable in C, a pointer to pointer in C is used to access/modify the value of a pointer variable. Here, the "value" of the former pointer is as usual a memory address. So, using a pointer to the pointer aka a double pointer in C, we can make the previous pointer point to another memory location.

Prerequisite

  • Pointers in C

Double Pointer Illustration

pointer to pointer in C

  • In essence, a double pointer in C holds the memory address of another pointer. This means that it provides an indirect reference to the variable the first pointer points to. Imagine it as a chain where the double pointer points to another pointer, which in turn points to the actual variable.

Declaration of Pointer to Pointer in C

  • To declare a double pointer, you utilize two asterisks before the variable name. Syntax: pointer_data_type **variable_name; For example:
  • Trying to make a double pointer directly point to a normal variable, like with int **double_ptr = &var; , will lead to a compiler warning. The correct approach is to point to a regular pointer.

Example of Double Pointer in C

A double pointer, also known as a pointer to a pointer, is a powerful concept in C programming. It allows you to indirectly access and modify variables through multiple levels of indirection. Here's a basic example to illustrate the usage of double pointers:

In this example:

  • We declare an integer variable value and initialize it with the value 42 .
  • We declare a pointer ptr1 and make it point to the address of value .
  • We declare a double pointer ptr2 and make it point to the address of ptr1 .

We then demonstrate how to access and modify the value of value using all three levels of indirection: directly using value , through ptr1 , and through ptr2 . Finally, we update the value through ptr2 and verify the change.

This example showcases the concept of double pointers and their ability to indirectly access and modify variables, making them a valuable tool in C programming.

How Double Pointer Works?

A double pointer, often referred to as a pointer to a pointer, is essentially a variable that stores the address of another pointer. In the C programming language, pointers are variables that hold memory addresses, typically of other variables. A double pointer takes this concept one level deeper.

Illustration

Imagine you have a box ( var ) that contains a value. Now, there's another box ( ptr ) that doesn't hold a direct value but rather a paper that tells you where the first box is located. This second box is a pointer. Now, imagine a third box ( double_ptr ), which instead of having a paper pointing to a direct value, has a paper pointing to the second box ( ptr ). This is the concept of a double pointer.

Explanation

Let's break it down step-by-step with code and explanation:

Regular Variable Declaration :

Here, an integer variable var is declared and assigned the value 10 .

Pointer Declaration :

An integer pointer ptr is declared, and it is assigned the address of the var variable.

Double Pointer Declaration :

Here, a double pointer double_ptr is declared, and it's assigned the address of the ptr pointer.

With this setup:

  • *ptr will give the value 10 (value of var ).
  • *double_ptr will give the address of var (because it points to ptr which holds the address of var ).
  • **double_ptr will give the value 10 (value of var ).

In essence, a double pointer provides an indirect way to access the value of the original variable. This level of indirection becomes useful, especially when dealing with dynamic data structures like linked lists, trees, and 2D arrays.

Size of Pointer to Pointer in C

  • Size is a key aspect to understand. While the data a pointer or double pointer refers to can be of various sizes, the pointers themselves typically have a fixed size, determined by the system architecture.
  • On a 32-bit system, a pointer generally occupies 4 bytes, while on a 64-bit system, it's typically 8 bytes. This size remains consistent regardless of whether it's a single or double pointer.

Example 1: Program to find the size of a pointer to a pointer in C

Application of double pointers in c.

  • Storing a list of strings : Double pointers can be used to create a dynamic array of strings, offering a space-efficient alternative to 2D arrays.
  • Dynamic memory allocation : Especially useful when dealing with 2D arrays. Instead of fixed-size arrays, using double pointers allows for flexible dimensions.
  • Command-line arguments : The main function in C accepts a double pointer, argv , which is an array of strings passed from the command line.

Multilevel Pointers in C

Multilevel pointers provide multiple layers of indirection in C. While double pointers are often used for applications like dynamic 2D arrays or arrays of strings, as we move beyond that, each additional level of indirection provides more flexibility but also introduces more complexity.

For instance:

  • A single pointer ( *ptr ) points to a variable.
  • A double pointer ( **ptr ) points to a single pointer, which in turn points to a variable.
  • A triple pointer ( ***ptr ) points to a double pointer, which points to a single pointer, eventually leading to the variable.

And the pattern can continue, though, in practical applications, you'll rarely see pointers with more than two levels of indirection.

Syntax of Triple Pointer in C

The declaration of a triple pointer involves three asterisks before the variable name. Here's how you can declare and use a triple pointer:

In the above example, ***triple_ptr provides three levels of indirection to access the value of var . First, it accesses the memory location of double_ptr , then ptr , and finally var .

  • Double pointers in C are very powerful and can have many applications (as explained in the Examples section) apart from simple data manipulation.
  • In most cases, it is a personal preference whether to make use of a double pointer or use a workaround. However, in certain scenarios, the use of double pointers becomes mandatory. One such example is if we want to store a list of variable sized strings in a space efficient manner or if the size of a 2D array can change during the course of program execution.
  • To change the value of a double pointer, we can use a "triple" pointer, which is a pointer to a pointer to a pointer (eg. int ***triple_ptr ). Similarly, to change the value of a triple pointer we can use a pointer to a pointer to a pointer to a pointer. In other words, to change the value of a "Level X" variable, we can use a "Level X+1" pointer. Thus, this concept can be extended to further levels.

Codeforwin

Pointer to Pointer (Double Pointer) in C

In previous two posts, we learned basics of pointers. We learned to create pointers and how to perform arithmetic operations on them.

We learned to create pointers to int and char . In real, you can have pointer to any type in C. You can have a pointer to int , char , float , double , structure, array or even pointer . In fact, you can declare pointer to pointer to pointer to pointer. That looks complex. For now, let us focus on pointer to pointer.

If a pointer points to a pointer of same type, we call it as pointer to a pointer. Read the statement slowly again, if you did not catch my words. Many texts and authors also refer pointer to pointer as double pointer , since two pointers are involved.

Pointer to Pointer (Double pointer) memory representation

In the above image pointer *ptr points at memory location 0x1230 of integer type. Pointer **dPtr points at memory location 0x1220 of integer pointer type .

Note: Pointer to pointer will always store address of a pointer of same type.

How to declare pointer to pointer (double pointer)

Pointer to a pointer declaration follows same declaration syntax as normal pointer declaration. The only thing you must care is it contains two * asterisks.

In general increase number of * asterisks during pointer declaration to increase pointer level.

Syntax to declare pointer to pointer

Here double ** specifies it as pointer to pointer (double pointer). Increase number of * asterisk with increase in pointing levels. Means for pointer to pointer to pointer use *** .

Example to declare pointer to pointer

The above statement declares a pointer to integer pointer type.

How to initialize pointer to a pointer (double pointer)

Like declaration, pointer to pointer initialization is also similar to simple pointer initialization. However, you must be cautious while initializing pointer to pointer. As it, accept address of a pointer variable of same type.

Example to initialize pointer to a pointer

How to access pointer to a pointer.

We use dereference * operator, to access value stored at memory location pointed by a pointer. However, single dereference will not work when dealing with pointer to a pointer. In order to access value pointed by pointer to a pointer we use double dereference ** (indirection) operator.

Example to access pointer to a pointer

Example program to use pointer to pointer.

Write a C program to demonstrate the use of pointer to a pointer.

Output –

Lloyd Rochester's Geek Blog

C double pointers, double pointers in c.

Updated December 19, 2022

Examples and explanations of single pointers are used throughout many programming languages including C. This blog post explains and explores use cases for double pointers in the C programming language. Toward the end we’ll look at a glibc example that uses a triple pointer.

The primary use cases I’ve found are the following:

  • Arrays of strings char * . These strings are typically not fixed length. Thus, char *buf[N] is a bit misleading since N will vary.
  • Functions that allocate memory for the caller. In this case the caller is expected to free the allocated memory after finished.

Mental Model

What is the difference between a char **foo and char *foo[] ? Let’s take an example program:

The following differences can be noted:

  • The string comparisons work with strcmp .
  • The sizeof compile time operator has different results as it’s the size of a pointer for a char * .
  • Memory for str1 and str2 are allocated differently. I don’t know enough to write about all the details.

Notice where the pointers are in memory:

It appears to me that str1 is on the stack. The contents of str2 is on the heap and the value of str2 is set in the main function.

Double Pointer Example 1

A great example to understand double pointers is using environment variables within a program in C. It looks like the following:

Let’s say we had the following environment variables: $ env SHELL = /bin/bash HOME = /home/lloyd

Here the char **environ is simply the following.

double char pointer in c

The memory looks something like the following. Note, this shows different environment variables SHELL and COLORTERM that what is above.

Double Pointer Example 2

This example is really to help understand Example 3. It skips the functions used in Example 3.

Here is some code to implement what is in the diagram. #include <stdlib.h> #include <assert.h> int main ( int argc, char * argv[]) { // &x = 0x7ffffffee074 int x; // &p = 0x7ffffffee068 // we never directly assign p int * p; // &pp = 0x7ffffffee078 int ** pp; x = 42 ; // point pp to p // &pp = 0x7ffffffee078, pp = 0x7ffffffee068 pp = & p; // changing *pp will change where p points to // *pp = 0x7ffffffee074, p = 0x7ffffffee074 * pp = & x; // by changing *pp we indirectly changed p // passes assert ( * p == 42 ); return EXIT_SUCCESS; }

In this example we indirectly assign p by de-referencing the double pointer pp . Through the double pointer pp we set the value of the single pointer p .

Double Pointer Example 3

This example solves a common problem where the caller has a pointer to a type and wants to call a function that allocates memory and typically initializes that type. The result of this function is the caller’s pointer will point to the allocated memory from that function. Effectively, it allows a caller to call a function that will allocate memory and point a pointer to that new memory. That’s a mouthful, but it happens. Don’t forget the caller is responsible to free this memory. Having another function allocate memory for a caller is common. It happens in C libraries where you see double pointers passed in. A function with double pointers is usually a dead giveaway that after the call this double pointer will be pointing to a newly allocated memory type. Unfortunately, this can’t be done with single pointers and let’s look at the example below to see why.

We can see from the example above for a function to allocate memory and assign the callers pointer to that memory the double pointer is required. This case is quite common and should be understood for any good C programmer. This example will shed light on what is going on inside many libraries that allocate memory for the caller.

Triple Pointer Example 4

The glibc system call to list files in a directory scandir() takes as argument a triple pointer for the namelist argument.

This is because inside the scandir function itself it will allocate a struct dirent **namelist for the caller. With this namelist it’s the same logically as a struct dirent *namelist[] , an array of pointers to struct dirent . Although, the caller doesn’t allocate the memory, the caller is expected to free the namelist .

There is a more thorough example to Listing files in a Directory using C .

Library homepage

  • school Campus Bookshelves
  • menu_book Bookshelves
  • perm_media Learning Objects
  • login Login
  • how_to_reg Request Instructor Account
  • hub Instructor Commons
  • Download Page (PDF)
  • Download Full Book (PDF)
  • Periodic Table
  • Physics Constants
  • Scientific Calculator
  • Reference & Cite
  • Tools expand_more
  • Readability

selected template will load here

This action is not available.

Engineering LibreTexts

12.5: Pointers to Pointers

  • Last updated
  • Save as PDF
  • Page ID 29108

  • Patrick McClanahan
  • San Joaquin Delta College

Double Pointer (Pointer to Pointer) in C

We already know that a pointer points to a location in memory and thus used to store the address of variables. So, when we define a pointer to pointer. The first pointer is used to store the address of the variable. And the second pointer is used to store the address of the first pointer. That is why they are also known as double pointers.

How to declare a pointer to pointer in C++? Declaring Pointer to Pointer is similar to declaring pointer in C. The difference is we have to place an additional ‘*’ before the name of pointer. Syntax :

Below diagram explains the concept of Double Pointers:

assign double pointer to single pointer

The above diagram shows the memory representation of a pointer to pointer. The first pointer ptr1 stores the address of the variable and the second pointer ptr2 stores the address of the first pointer.

Remember how the pointer works - we saw the next image in a previous section...just for a reminder.

Let us understand this more clearly with the help of the program below:

We have an integer variable, a pointer variable and a pointer to a pointer variable. Really, all we are doing is passing around the address of the integer variable, As you can see in the output below, the address is the same, and accessing the value is gives us that same value..

Here is the output:

Pointers to pointers can be useful...as long as you realize its just addresses, you can keep it straight in your mind

Adapted from: "Double Pointer (Pointer to Pointer) in C"  by  Harsh Agarwal ,  Geeks for Geeks  

  • C++ Language
  • Ascii Codes
  • Boolean Operations
  • Numerical Bases

Introduction

Basics of c++.

  • Structure of a program
  • Variables and types
  • Basic Input/Output

Program structure

  • Statements and flow control
  • Overloads and templates
  • Name visibility

Compound data types

  • Character sequences
  • Dynamic memory
  • Data structures
  • Other data types
  • Classes (I)
  • Classes (II)
  • Special members
  • Friendship and inheritance
  • Polymorphism

Other language features

  • Type conversions
  • Preprocessor directives

Standard library

  • Input/output with files

Address-of operator (&)

assign double pointer to single pointer

Dereference operator (*)

assign double pointer to single pointer

  • & is the address-of operator , and can be read simply as "address of"
  • * is the dereference operator , and can be read as "value pointed to by"

Declaring pointers

Pointers and arrays, pointer initialization, pointer arithmetics.

assign double pointer to single pointer

Pointers and const

Pointers and string literals.

assign double pointer to single pointer

Pointers to pointers

assign double pointer to single pointer

  • c is of type char** and a value of 8092
  • *c is of type char* and a value of 7230
  • **c is of type char and a value of 'z'

void pointers

Invalid pointers and null pointers, pointers to functions.

assign double pointer to single pointer

C – Pointer To Pointer (Double Pointer)

C – Pointer To Pointer

Table of Contents

A pointer-to-pointer (double pointer) is used to store the address of another pointer. The first pointer stores the address of a variable, and the second pointer stores the address of the first pointer. This makes them useful for changing the values of normal pointers or creating variable-sized 2-D arrays. Importantly, a double pointer occupies the same amount of memory as a regular pointer on the stack.

Declaration of Pointer to a Pointer in C

We know that declaring a pointer will be similar to declaring a double pointer in C. The only difference, we can notice is the adding of * just before the pointer name.

Therefore, this diagram illustrates the first pointer ptr 1 will store the address of the variable and the second pointer ptr 2 can store the address of the first pointer.

Practice Real Interview Coding Questions

Example of double pointer in c, how double pointer works.

Int var =10;

int*ptr =&var;

Int**ptr=&ptr;

  • Declare a double-pointer with the appropriate syntax.
  • Store the address of another pointer as the value of the double-pointer.
  • To manipulate or dereference to any of its levels, use the asterisk ( * ) operator the number of times needed to reach the desired level.

Size of Pointer to Pointer in C

A double-pointer acts similarly to a normal pointer in C. Also, the size of the pointer is equal to a double pointer.

Example 1: C Program to find the size of a pointer to a pointer

The size of a pointer in C is not fixed and can vary based on factors like CPU architecture and the operating system. Typically, for a 64-bit operating system, pointer sizes are 8 bytes, while for a 32-bit operating system, they are 4 bytes. This size variation is important to consider when working with pointers, especially when dealing with memory allocation and ensuring your code is compatible across different platforms and systems.

Application of Double Pointers in C

  • Dynamic Memory Allocation: Double-pointers are used to allocate and manage memory for multidimensional arrays, enabling flexible data structures.
  • Multilevel Data: They are used to store and manage complex hierarchical data structures, like text documents with paragraphs, sentences, and words.
  • Data Structures: In data structures, double-pointers allow direct manipulation of node addresses without copying data, improving efficiency.
  • Function Arguments: Double-pointers can be used as function arguments to modify the addresses stored in local pointers, facilitating efficient data manipulation.

Multilevel Pointers in C

  • In C, we have multilevel pointers beyond double pointers.
  • For changing the value of a double pointer, we can use a triple pointer, such as int ***t_ptr .
  • Syntax: pointer_type ***pointer_name;

Syntax of Triple Pointer

  • This concept extends further, allowing us to use “level – x + 1” pointers to change the value of a “level – x” variable, and this can be carried to higher levels as needed.

FAQ- C – Pointer To Pointer (Double Pointer)

Q1. how to return a double pointer array in c.

Ans. Declaring a 2D array like int input[][c_in] doesn’t make the computer interpret these as pointers. input[x][y] represents integers directly, not memory addresses. If you’re getting addresses when printing, check your code for any issues. Use printf("%d", input[x][y]); to print integer values.

Q2. What is the advantage of a double-pointer?

Ans. Double pointers in C are powerful tools for efficiently managing data in memory. They allow you to access and manipulate memory addresses, making them versatile for tasks like data reorganization. A pointer, as the name suggests, points to a specific location in memory, enabling you to work with data effectively.

Q3. What are the two types of pointers in C?

Ans. Those are four types of pointers. Those are : Null Pointer. Void Pointer. Wild Pointer. Dangling Pointer.

Hridhya Manoj

Hello, I’m Hridhya Manoj. I’m passionate about technology and its ever-evolving landscape. With a deep love for writing and a curious mind, I enjoy translating complex concepts into understandable, engaging content. Let’s explore the world of tech together

What Is The Internal And External Fragmentation In OS?

Advantages and Disadvantages Of HTML

Leave a Comment Cancel reply

Save my name, email, and website in this browser for the next time I comment.

Reach Out to Us for Any Query

SkillVertex is an edtech organization that aims to provide upskilling and training to students as well as working professionals by delivering a diverse range of programs in accordance with their needs and future aspirations.

© 2024 Skill Vertex

Software Development Resources by David Egan.

Double pointers and linked list in c.

This article will (hopefully) demonstrate the usefulness of double pointers (multiple indirection) in manipulating linked list elements efficiently.

Intro to Linked Lists

A linked list is an abstract data structure that is made up of a collection of nodes (or elements). Lists nodes are accessed by means of sequential access - they are accessed in an ordered/predetermined sequence.

List objects can be stored anywhere in memory - they do not need to be next to one another. This makes it easy to insert new elements, but has the disadvantage of requiring sequential access when accessing values.

Linked List Using Double Pointers

For the current example, nodes are dynamically allocated (using malloc() ) and each node consists of a data field and a reference (a pointer) to the next node in the list. In the case of the last node in the list, the next field contains NULL - it is set as a null pointer.

Our nodes are defined with a C struct - for the purposes of this exercise, nodes are defined as NODE using typedef . The data field of the node consists of a single char *name member variable:

After this typedef declaration, NODE *head defines a variable head which is a pointer to a node struct pointer.

For the sake of simplicity this example will consider two actions:

  • prepend() : add a node to the start (head) of the list
  • append() : add a node at the end of the list

A pointer is a variable that stores the memory address of another variable. In C, you need to define the type of the object that is being pointed at.

For example: int a = 42; int *pNum = &a; .

The variable pNum now contains the address of a , which is the memory location of an object having the data type integer. Dereferencing the pointer variable *pNum instructs the programme to return the integer value that is held at the memory address returned by pNum .

NOTE: you shouldn’t try to dereference a null pointer in C - this produces undefined behaviour.

Initialise the Linked List

The list is initialised by creating a NODE *head which is set to NULL . The variable head is now a pointer to NULL , but as NODE s are added to the list head will be set to point to the first NODE . In this way, head becomes the access point for sequential access to the list.

Adding Nodes

As the first node is added, the head pointer is amended to point to the new node, and the next pointer of the new node points to NULL . In the case of the first node, append() and prepend() have exactly the same effect.

In each case, a node needs to be created. To achieve this:

Why Double Pointers?

Arguments are always passed to functions by value in C. In other words, when C passes control to a function, a copy of each argument is made and this copy is passed to the function - leaving the original variable unchanged.

In order to amend a variable in a calling function from within a called function, you need to pass a pointer to the variable as a function argument. This provides the called function with the memory address of the variable to be amended. Dereferencing this (pointer) variable within the called function provides access to the original value.

Simplified example:

In the function definition for prepend() shown below, the first parameter is NODE **head . This specifies that the function receives a variable with the pointer to pointer variable type NODE ** . In other words, the function receives an address of a variable which is in turn a pointer to a NODE - in this case, the function argument is the address of the variable NODE *head which is a pointer that points to either the first node in the list or to NULL .

If a new node is added to the head of the list (by means of a prepend() action), the head pointer is amended to point to the new node and the next field of the new node refers to the address of the second (previously first) node.

This is the easier function to understand:

In the case of the new node being the first node in the list, head == NULL so the assignment newNode->next = *head correctly sets the next field of the last node (in this case, also the first node) to NULL .

If the list already contains nodes, the head variable holds a pointer to a pointer to the existing first node. Note that the address of head is passed into the prepend() function from the caller.

Because we want to insert the new node before the existing first node, the next field of the new node should point to the address of the existing first node. The declaration newNode->next = *head correctly makes this assignment.

Setting the new head reference is where double pointers become useful. Because we pass in the address of the head variable rather than the variable itself, we can access (and amend) it’s value from within the prepend() function. When the *head is set to the address of the new node from within prepend() we are saying:

“Dereference **head once to get the memory address that is held by head in the calling function, and set this address to the address of the new node.”

Append Node

If a new node is added to the end of the list (by means of append() , the next field of the previously last node is amended to point to the memory address of the new node. If the appended node is also the first node in the list, then the head pointer must be amended to point to the new node.

In this case, the challenge is to efficiently find the last node, whilst accounting for the possibility that this may be the first node in the list. Note that in any case the next field of the new node points to null.

Create a tracer and set this initially to hold the memory address of head. Set tracer to the address of the pointer to the next NODE . In the case of an empty list or the last NODE , this value will be NULL .

NOTE: *tracer dereferences tracer once, so it refers to a pointer to a NODE .

The arrow operator can then be used to indirectly access the member variable. The following are equivalent:

  • tracer = &(*tracer)->next;
  • tracer = &(*(*tracer)).next;
  • tracer = &(**tracer).next;

Note that tracer must be a pointer to a pointer to a NODE - it must contain the memory address of a pointer to a NODE (i.e. NODE * ).

After the loop, *tracer will be a pointer to NULL even if the list is empty. *tracer now refers to the pointer to the next node of the last node. Currently NULL , the next line refers it to the new NODE .

  • struct (C Programming Language)
  • Sequential Access
  • Pros and cons of linked lists

Recent Posts

  • Branch Management With Git Worktree
  • Cargo Add for Dependency Management
  • Rules of Borrowing in Rust
  • Add Methods To An Existing Type in Go
  • Use Delve to Run and Debug a Single Unit Test in Go
  • Virtualenv & Virtualenvwrapper Setup in Python 3 on Ubuntu Focal Fossa
  • LUKS Encrypt Hard Drive with Cryptsetup on Ubuntu 20.04
  • Bitcoin Pay To Script Hash
  • Access YAML Values from Frontmatter Using Python
  • Build Bitcoin Core in Ubuntu

IMAGES

  1. Double Pointer (Pointer to Pointer) in C

    assign double pointer to single pointer

  2. C

    assign double pointer to single pointer

  3. C

    assign double pointer to single pointer

  4. How do pointer-to-pointers work in C? (and when might you use them

    assign double pointer to single pointer

  5. C Double Pointer (Pointer to Pointer) ~ College Term Work Blog

    assign double pointer to single pointer

  6. Double Pointer in C

    assign double pointer to single pointer

VIDEO

  1. Pointer Aliasing

  2. Array of pointers vs pointer to an array #mysirg

  3. Pointer to Pointer Variable || Double Pointer in C Language #cprogramming #computerlanguage

  4. Extra Problems 1 Pointers double pointers tracing inside function

  5. Basic pointer

  6. Pointers in C -Lecture 4(Double Pointer)

COMMENTS

  1. How to assign single pointer into double pointer

    How to assign single pointer into double pointer Ask Question Asked 5 years, 8 months ago Modified 5 years, 8 months ago Viewed 1k times 0 So I saw this example: int main () { char *ls [] = {"ls", NULL}; char *grep [] = {"grep", "pipe", NULL}; char *wc [] = {"wc", NULL}; char **cmd [] = {ls, grep, wc, NULL}; loop_pipe (cmd); return (0); }

  2. C

    { int var = 789; int* ptr2; int** ptr1; ptr2 = &var; ptr1 = &ptr2; printf("Value of var = %d\n", var); printf("Value of var using single pointer = %d\n", *ptr2); printf("Value of var using double pointer = %d\n", **ptr1); return 0; } Output Value of var = 789 Value of var using single pointer = 789 Value of var using double pointer = 789

  3. C++ Pointer To Pointer (Double Pointer)

    Courses Practice Video In C++ a Pointer is a variable that is used to store the memory address of other variables. It is a variable that points to a data type (like int or string) of the same type and is created with the * operator. Syntax of a Pointer in C++: data_type_of_pointer *name_of_variable = & normal_variable;

  4. A Complete Guide to using Double Pointer in C: Pointer-to-Pointer

    The syntax to declare a double pointer in C is: 1. int **doubleptr; In this example, the variable doubleptr is a double pointer to an integer value. The ** notation is used to indicate that doubleptr is a pointer to a pointer. To initialize a double pointer, you can use the address of operator & on a pointer variable, like this:

  5. C

    When a pointer holds the address of another pointer then such type of pointer is known as pointer-to-pointer or double pointer. In this guide, we will learn what is a double pointer, how to declare them and how to use them in C programming. To understand this concept, you should know the basics of pointers.

  6. C program to demonstrate example of double pointer (pointer to pointer)

    To store address of a pointer variable, we use a double pointer which is also known as pointer to pointer. In this C program, we will understand how to declare, assign and access a double pointer (pointer to pointer)? C program for double pointer (pointer to pointer)

  7. C

    A double pointer, also known as a pointer to a pointer, is a powerful concept in C programming. It allows you to indirectly access and modify variables through multiple levels of indirection. Here's a basic example to illustrate the usage of double pointers:

  8. Pointer to Pointer (Double Pointer) in C

    Increase number of * asterisk with increase in pointing levels. Means for pointer to pointer to pointer use ***. Example to declare pointer to pointer int ** ptr; The above statement declares a pointer to integer pointer type. How to initialize pointer to a pointer (double pointer)

  9. C Double Pointers

    Double Pointer Example 1 A great example to understand double pointers is using environment variables within a program in C. It looks like the following: #include <stdlib.h> #include <stdio.h> extern char **environ; int main(int argc, char *argv []) { char **ep; for(ep = environ; *ep != NULL; ep++) { puts(*ep); } return EXIT_SUCCESS; }

  10. Introduction to a Double Pointer C++ (Pointer to a Pointer)

    In this tutorial, I demonstrate a simple example using a double pointer a.k.a. pointer to a pointer (not to be confused with a double * which is single point...

  11. 12.5: Pointers to Pointers

    Here is the output: Address of newVar: 0x7ffe33b7c834 Address contained in newPtr: 0x7ffe33b7c834 Address contained in dblPtr: 0x7ffe33b7c834 Value of newVar = 789 Value of newVar using single pointer, *newPtr = 789 Value of newVar using double pointer, **dblPtr = 789

  12. Pointers

    Pointers are a very powerful feature of the language that has many uses in lower level programming. A bit later, we will see how to declare and use pointers. Dereference operator (*) As just seen, a variable which stores the address of another variable is called a pointer. Pointers are said to "point to" the variable whose address they store.

  13. Use of Double Pointers in C?

    The function takes a double pointer "pp" as its argument, which means that it can modify the original pointer value by dereferencing the pointer-to-pointer "*pp" and assigning a new memory ...

  14. C

    How Double Pointer Works? Int var =10; int*ptr =&var; *ptr=20; Int**ptr=&ptr; **ptr=30; Declare a double-pointer with the appropriate syntax. Store the address of another pointer as the value of the double-pointer.

  15. double pointer to single pointer

    return 1; else if (pa->value < pb->value) return -1; return 0; } they are converting to double pointer to single pointer. item* pa = * (item**) a; item* pb = * (item**) b; when I try that code, double pointer to single pointer is not working fine.Following code only working for me. item pa = * (item**) a; item pb = * (item**) b;

  16. Pointer Basics

    The null pointer is the only integer literal that may be assigned to a pointer. You may NOT assign arbitrary numbers to pointers: int * p = 0; // okay. assignment of null pointer to p int * q; q = 0; // okay. null pointer again. int * z; z = 900; // BAD! cannot assign other literals to pointers! double * dp; dp = 1000; // BAD!

  17. Double Pointers and Linked List in C

    Pointers. A pointer is a variable that stores the memory address of another variable. In C, you need to define the type of the object that is being pointed at. For example: int a = 42; int *pNum = &a;. The variable pNum now contains the address of a, which is the memory location of an object having the data type integer.

  18. c

    1 if use pointer, then pass by pointer, not by value. If use double pointer, pass address of pointer. If want to pass value, pass without any pointers.

  19. C assign value to double pointer

    struct ABC* hoho = (struct ABC*) (mem_malloc (sizeof (struct ABC))); The variable hoho can be assigned, and its members can be accessed without ease, working both on my computer and the STM32. Please note that all the code works on my laptop, and most data types work for the STM32 too.

  20. c++

    Although reference and pointer arguments may (likely) be implemented with similar internal mechanics, a reference is not a pointer (see: What are the differences between a pointer variable and a reference variable?) and, as such, using one in lieu of the other is undefined behaviour.. Thus, a significant drawback of what you're doing in the shown code is that it produces undefined behaviour.