Select Page

Multiple levels of indirections

by 19.03.2023C pointers

It is common to see a variable declared as pointer to a pointer. We call such variable “a double pointer”. One of examples can be when program arguments are passed to the main function. These parameters are usually named argc and argv.

Strings

There are various ways to declare a string such as:

  • string str = “Hello!”;
  • char *str = “Hello!”;

Let’s start with a simple example of double pointer:

#include <stdio.h>

int	main(void)
{
	char	*str;
	char	**ptrtostr;

	str = "hello";
	printf("str: %s\n", str);
	ptrtostr = &str;
	printf("ptrtostr: %s\n", *ptrtostr);
	return (0);
}
Terminal> gcc DoublePointer2.c
Terminal> ./a.out
str: hello
ptrtostr: hello

Above you can see graphical description of double pointer and the simple program for illustration.

#include <stdio.h>

void	display(char **ptrtostr)
{
	printf("First line of function display: %s\n", *ptrtostr);
	*ptrtostr = "This is our second string.\n";
}

int	main(int argc, char **argv)
{
	char	*str;

	str = "This is our first string.";
	printf("Before call of function display: %s\n", str);
	display(&str);
	printf("After call of function display: %s", str);
	return (0);
}

Terminal > gcc DoublePointer.c
Terminal > ./a.out
Before call of function display: This is our first string.
First line of function display: This is our first string.
After call of function display: This is our second string.

As seen in the example above, if you have a pointer that you want to change in another function, it is necessary to use the double pointer. Dereferencing once *ptrtostr looks at the address of str and we assign it a different value.

What are the double pointers used for?

Double pointers are often used in C to allow functions to modify the value of a pointer passed as an argument.

Double pointers can bu used in some advanced data structures such as:

  • Linked lists,
  • Trees,
  • Graphs.

In these cases, double pointers are used to create and manipulate nodes, which themselves contain pointers to other nodes.

SOURCES:

[1] Understanding and Using C Pointers by Richard Reese (O’Reilly). Copyright 2013 Richard Reese, Ph.D. 978-1-449-34418-4
[2] PRINZ, Peter a Tony. C in a Nutshell: THE DEFINITIVE REFERENCE. 2nd Edition. Sebastopol: O’REILLY, 2016. ISBN 978-1-491-90475-6.
[3] CodeVault, 2016, IWhat are double pointers in C?, YouTube video. [2023-03-19]. Available at: https://youtu.be/jUcqT37FdUI .
[4] ChatGPT