CProgramming Tutorial

  • C Programming Tutorial
  • C - Overview
  • C - Features
  • C - History
  • C - Environment Setup
  • C - Program Structure
  • C - Hello World
  • C - Compilation Process
  • C - Comments
  • C - Keywords
  • C - Identifiers
  • C - User Input
  • C - Basic Syntax
  • C - Data Types
  • C - Variables
  • C - Integer Promotions
  • C - Type Conversion
  • C - Constants
  • C - Literals
  • C - Escape sequences
  • C - Format Specifiers
  • C - Storage Classes
  • C - Operators
  • C - Decision Making
  • C - While loop
  • C - Functions
  • C - Scope Rules
  • C - Pointers
  • C - Strings
  • C - Structures
  • C - Bit Fields
  • C - Typedef
  • C - Input & Output
  • C - File I/O
  • C - Preprocessors
  • C - Header Files
  • C - Type Casting
  • C - Error Handling
  • C - Recursion
  • C - Variable Arguments
  • C - Memory Management
  • C - Command Line Arguments
  • C Programming Resources
  • C - Questions & Answers
  • C - Quick Guide
  • C - Useful Resources
  • C - Discussion
  • Selected Reading
  • UPSC IAS Exams Notes
  • Developer's Best Practices
  • Questions and Answers
  • Effective Resume Writing
  • HR Interview Questions
  • Computer Glossary

C - Pointer to Pointer

A pointer to a pointer is a form of multiple indirection, or a chain of pointers. Normally, a pointer contains the address of a variable. When we define a pointer to a pointer, the first pointer contains the address of the second pointer, which points to the location that contains the actual value as shown below.

Pointer to Pointer in C

A variable that is a pointer to a pointer must be declared as such. This is done by placing an additional asterisk in front of its name. For example, the following declaration declares a pointer to a pointer of type int −

When a target value is indirectly pointed to by a pointer to a pointer, accessing that value requires that the asterisk operator be applied twice, as is shown below in the example −

When the above code is compiled and executed, it produces the following result −

Pointer Basics

Section 1 -- pointer rules, 1) pointers and pointees, 2) dereferencing, 3) pointer assignment, section 2 -- binky's code example, java version, c++ version, pascal version, section 3 -- study questions.

  • 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 (&)

set pointer to another pointer c

Dereference operator (*)

set pointer to another pointer c

  • & 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.

set pointer to another pointer c

Pointers and const

Pointers and string literals.

set pointer to another pointer c

Pointers to pointers

set pointer to another pointer c

  • 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.

Dot Net Tutorials

Pointer to Pointer in C 

Back to: C Tutorials For Beginners and Professionals

Pointer to Pointer in C Language with Examples

In this article, I will discuss Pointer to Pointer in C Language with Examples. Please read our previous articles discussing Arithmetic Operations on Pointers in C Language with Examples. In C programming, a pointer to a pointer is a form of multiple indirection or a chain of pointers. Normally, a pointer stores the address of a variable. Similarly, a pointer to a pointer is a variable that stores the address of another pointer.

Pointer to Pointer (Double Pointer) in C Language:

It is a concept of holding the pointer address into another pointer variable. In C Language, a pointer variable points to a location in memory and is used to store the address of a variable. In C, we can also define a pointer to store the address of another pointer. Such a pointer is called a double pointer (pointer to pointer). So, when we define a pointer to a 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. This is the reason why they are also called double-pointers.

Pointer to Pointer in C Language with Examples

In C programming language, the pointer-to-pointer relations can be applied up to 12 stages, but generally, there are no limitations. For a pointer variable, we can apply 12 indirection operators. When we are using the pointer-to-pointer relations, then performance will be decreased.

How to Declare a Pointer to Pointer in C?

Declaring a Pointer to a Pointer or double-pointer is similar to declaring a pointer in C. The difference is we have to place an additional * before the pointer’s name. Syntax: int **ptr;

Understanding Pointer to Pointer in C

Consider a regular pointer: int x = 10; int *p = &x; // ‘p’ is a pointer to ‘x’

Here, p is a pointer that holds the address of x. Now, let’s introduce a pointer to a pointer:

int **pp = &p; // pp is a pointer to p, which is a pointer to x Here, pp is a pointer to a pointer. It holds the address of p, which in turn holds the address of x.

Dereferencing a Pointer to Pointer

Dereferencing a pointer to a pointer involves an extra level of indirection:

  • *pp dereferences pp to get p.
  • **pp dereferences pp to get p, and then again dereferences p to get the value of x.

Here’s a simple example demonstrating the use of a pointer to a pointer:

Example to understand Pointer to Pointer in C :

Example to understand Pointer to Pointer in C

Example: Pointer to Pointer in C Language

Output: 10 10 10 10

For a better understanding of the above program, please have a look at the following diagram.

Pointer-to-Pointer in C Language with Examples

How the logic is evaluated in the above Program:

Pointer-to-Pointer in C

Use Cases for Pointers to Pointers in C Language:

  • Dynamic Memory Allocation: In functions that dynamically allocate memory and need to return a pointer to this memory, a pointer to a pointer can be used.
  • Modifying a Pointer in a Function: To modify a pointer itself in a function (not the value it points to), you must pass it to that pointer.
  • Arrays of Strings: An array of strings can be represented as an array of pointers to characters. If you want to manipulate this array (like reallocating it), a pointer to a pointer is used.
  • Implementing Data Structures: In complex data structures like trees or linked lists, pointers to pointers can be used to handle nodes effectively.
  • Function Pointers Array: For an array of function pointers, if the functions themselves take pointers as arguments, you might end up with pointers to pointers.

Example: Basic Usage of Pointer to Pointer

In this example, var is a normal integer variable, ptr is a pointer that holds the address of var, and pptr is a pointer to ptr, i.e., it holds the address of ptr. The **pptr expression allows us to access the value of var.

Example: Modifying Values

In this example, the function addOne is designed to take a pointer to a pointer to an integer. It dereferences it twice to increment the value of the actual integer value.

Example: Arrays of Strings

Here, names is an array of pointers to char. Each element in names points to the first character of a string.

Example: Dynamic Memory Allocation

In this final example, arr is a pointer to a pointer used to create a 2D dynamic array. Memory is allocated for each row and column, and then it is freed at the end of the program to avoid memory leaks.

Key Points:

  • Pointer to pointer adds an additional level of indirection, making it more complex, but is is also powerful.
  • It’s commonly used for dynamic memory allocation, handling multiple strings, and in complex data structures.
  • Care should be taken to manage memory effectively to avoid leaks.

In the next article, I will discuss Pointer to an Array of Functions in C language. In this article, I try to explain Pointer to Pointer in C Language with Examples. I hope you enjoy this Pointer to Pointer in C Language with Examples article. I would like to have your feedback. Please post your feedback, questions, or comments about this article.

dotnettutorials 1280x720

About the Author: Pranaya Rout

Pranaya Rout has published more than 3,000 articles in his 11-year career. Pranaya Rout has very good experience with Microsoft Technologies, Including C#, VB, ASP.NET MVC, ASP.NET Web API, EF, EF Core, ADO.NET, LINQ, SQL Server, MYSQL, Oracle, ASP.NET Core, Cloud Computing, Microservices, Design Patterns and still learning new technologies.

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

An Essential Guide to Pointers in C Programming

Pointers are vital to many C programs, but they can be difficult to understand. Review their syntax and how they work with practical examples.

Pointers are an essential aspect of C programming that you’ll need a good understanding of to use the language effectively. They aid in efficient memory management, passing data by reference, handling arrays and strings, and more. However, they require careful use to avoid errors.

Explore the details of C pointers, from understanding memory and addresses to mastering pointer arithmetic.

Memory and Addresses

A close-up of an internal computer part.

Memory—often used as a shorthand for RAM (Random Access Memory) —is the storage space in a computer that holds the data and instructions a program needs to run. It serves as the workspace for your program. The smallest unit of memory is typically a byte, which is equal to eight bits.

Each memory location has a unique address and can store a different amount of data depending on the computer. When you declare a variable in C, you’re implicitly assigning it a memory location to store its data. Think of it like a house, which has a unique address that you can use to locate it.

Imagine your computer's memory as a sequence of storage cells, each containing a byte of data. Let's say there are two variables, x and y , in a C program:

In memory, it might look like this:

Here, separate memory locations store these variables. The data that x represents resides at memory address 1000, while y ’s data occupies memory address 1004.

Understanding memory and addresses is crucial when you're working with pointers because they are variables that store memory addresses. They let you access and manipulate data stored in a specific memory location.

Declaring and Initializing Pointers in C

Before you can modify data using pointers in C, you need to declare and initialize it.

Declaration

To declare a pointer, you specify the data type it points to, followed by an asterisk (*), and then the pointer's name. For example:

Here, int *ptr declares a pointer named ptr that can store the memory address of an integer.

Initialization

After declaration, you should initialize it with the memory address it will point to. You can initialize it like this:

In this declaration, the & operator fetches the address of the x variable. The code essentially says "ptr is a variable, it stores the memory location of an integer value, and that location is wherever x currently refers to."

Now, ptr holds the address of the integer variable x . For instance:

Pointers in C not only store the address of a variable but also have their own unique address within the computer's memory.

Dereferencing Pointers

Dereferencing a C pointer means accessing the value stored at the memory address pointed to by the pointer.

Suppose you have a pointer, int *ptr , that points to an integer variable, and that variable has a value of 10. To access the value through the pointer, you use the asterisk ( * ) operator:

This example uses the ptr variable to retrieve the value at the memory address it points to. So, value now holds the value 10, which is the content of x .

Pointer Arithmetic

Pointer arithmetic is a powerful feature in C, especially useful for working with arrays and strings (which are arrays of characters). It lets you perform arithmetic operations on pointers to move around in memory.

Here’s an example showing how you can use it.

Begin by declaring an array of integers:

Declare a pointer to an int and assign the memory location of the numbers array to it:

You do not need to use the "&" operator here because numbers is already, implicitly, a pointer type.

The ptr variable now points to the first element in the array:

You can move the pointer to the third element of the array by incrementing it by 2:

You can move the pointer backward by subtracting from it:

Pointer arithmetic is particularly useful for navigating arrays and working with dynamic memory allocation.

Pointers and Functions in C

If you understand how functions work in C programming , then you're well on your way to using function pointers. Here are some ways you can use them.

Function Pointers

You can declare and use function pointers to use functions dynamically, just like any other value. This is particularly useful for callbacks and dynamic function execution.

This code declares a function pointer named operation that can point to a function that takes two integers and returns one. It assigns (a pointer to) the add function to operation . It then uses the operation variable to indirectly call add(5, 3) .

  • Passing by Reference

Pointers allow you to pass arguments by reference to functions, enabling you to modify the original data within the function. This is crucial for functions that need to change the value of a variable outside their scope.

The modifyValue function alters the value of whatever argument the calling code supplies to it, setting it to 42.

  • Dynamic Memory Allocation

Functions can return pointers to dynamically allocated memory. This is common when you need to create and return unbounded data structures like arrays or linked lists. You’ll need to have a good grasp of stack and heap memory to use it.

This code defines a function, createArray , that takes an integer, size , as input. Inside the function, it dynamically allocates memory for an integer array of the specified size using malloc . After initializing the array, it returns a pointer to this newly created array.

Common Uses

Pointers are essential in C for several reasons, and they are what distinguish C from other programming languages like Python . Here are some common uses:

  • Array Manipulation
  • Data Structures
  • Resource Management

Understanding these common uses of pointers can enhance your C programming skills. Practice some of these to improve your understanding of pointers.

Practice Using Pointers in C Programming

Mastering pointers in C programming is a valuable skill that enables you to efficiently manage memory, manipulate data, and perform advanced operations. Practice and proficiency with pointers will greatly improve your ability to create robust and resource-efficient C programs.

How to Use Pointers in C Programming

If you are learning C programming, you have probably heard the term "pointer" before.

Pointers are one of the most important and powerful features of the C programming language. They allow us to manipulate memory directly, which can be very useful in many programming scenarios.

In C, a pointer is simply a variable that holds a memory address. We can think of it as a way to refer to a specific location in memory.

How to Declare a Pointer

To declare a pointer variable in C, we use the asterisk * symbol before the variable name. There are two ways to declare pointer variables in C:

Both of these declarations are equivalent and they declare a pointer variable named "p" that can hold the memory address of an integer.

However, it's important to note that if you declare multiple variables in a single statement, you need to include the asterisk before each variable name to indicate that they are all pointers. For example:

This declares three pointer variables named "p", "q", and "r" that can hold the memory address of an integer.

How to Initialize a Pointer

When we declare a pointer variable, it does not automatically point to any particular memory location. To initialize a pointer to point to a specific variable or memory location, we use the ampersand & operator to get the address of that variable.

For example, to initialize the pointer p to point to an integer variable called x , we would write:

This sets the value of p to be the memory address of x .

How to Dereference a Pointer

Once we have a pointer that points to a specific memory location, we can access or modify the value stored at that location by dereferencing the pointer.

To dereference a pointer, we use the asterisk * symbol again, but this time in front of the pointer variable itself. For example, to print the value of the integer that p points to, we would write:

What Does "Pointer to a Pointer" Mean?

A pointer can also point to another pointer variable. This is known as a "pointer to a pointer". We declare a pointer to a pointer by using two asterisks ** . For example:

Here, q is a pointer to a pointer. It points to the address of the p variable, which in turn points to the address of the x variable

How to Pass Pointers to Functions

We can pass pointers to functions as arguments, which allows the function to modify the value of the original variable passed in. This is known as "passing by reference".

To pass a pointer to a function, we simply declare the function parameter as a pointer. For example:

Here, the increment function takes a pointer to an integer ( int *p ) and increments the value of the integer by one ( (*p)++ ).

In main() , we declare the integer x and a pointer p that points to x . We then call the increment function, passing in the p pointer. After the function call, x has been incremented to 43 .

How to Use Pointers for Dynamic Memory Allocation

One of the most powerful uses of pointers in C is for dynamic memory allocation. This allows us to allocate memory at runtime, rather than at compile time.

We use the malloc function to dynamically allocate memory, and it returns a pointer to the allocated memory. For example:

Here, p is a pointer to an integer that has been allocated using malloc . The sizeof operator is used to determine the size of an integer in bytes.

After allocating memory, we can use the pointer variable like any other pointer. When we are finished with the memory, we should free it using the free function. For example:

This frees up the memory that was allocated to p .

What is Pointer Casting?

Sometimes you may need to cast a pointer from one type to another. You can do this using the (type *) syntax. For example:

Here, p is cast to a pointer to a double type.

How Does Pointer Arithmetic Work?

Because pointers hold memory addresses, we can perform arithmetic operations on them to move them to different memory locations.

For example, we can increment a pointer to move it to the next memory location. This is often used in array operations, where we use a pointer to access elements of an array.

For example, to print the first element of an integer array using a pointer, we could write:

Here, p is set to point to the first element of the arr array, and *p dereferences the pointer to get the value of the first element (which is 1 ).

How to Use Pointer Arrays

We can also declare arrays of pointers in C. For example:

This declares an array of three pointers to integers. Each element of the array can point to a separate integer variable.

Pointer Arithmetic and Arrays

We can use pointer arithmetic to access elements of an array. For example:

Here, p is set to point to the first element of the arr array. We can use pointer arithmetic to access the second element of the array ( *(p + 1) ), which is 2 .

Example of How to Use Pointers

Here's an example program that demonstrates some of the concepts we've discussed:

Screenshot-from-2023-05-01-12-03-41

This program demonstrates several concepts related to pointers.

First, we declared an integer variable x and a pointer p that points to x . We called the increment function, passing in the p pointer. The increment function modifies the value of x by incrementing it by one. We then printed the value of x before and after the function call to demonstrate that x has been incremented.

Next, we used dynamic memory allocation to allocate an array of three integers. We set the values of the array elements using pointer arithmetic ( arr[0] = 1 , arr[1] = 2 , etc.). We then declared a pointer q that points to the first element of the array. Furthermore, we used pointer arithmetic to access and print the values of each element of the array.

Finally, we freed the memory that was allocated to the array using the free function.

This program demonstrates how pointers can be used to modify the value of a variable, access elements of an array using pointer arithmetic, and dynamically allocate and free memory.

Common Pointer Errors

Pointers can be tricky to work with, and they can lead to some common errors.

One common error is using an uninitialized pointer. If you declare a pointer variable but do not initialize it to point to a valid memory location, you may get a segmentation fault or other error when you try to dereference the pointer.

Another common error is dereferencing a null pointer, which can also cause a segmentation fault.

Another error to be aware of is using the wrong type of pointer. For example, if you declare a pointer to an integer but then try to dereference it as a pointer to a character, you may get unexpected results or errors.

Pointers are a powerful tool in C programming, but they can be a bit tricky to work with. With practice and patience, you can master pointers and use them to manipulate memory and work with complex data structures.

Thank you for reading!

A curious full-stack web developer. I love solving problems using software development and representing Data in a meaningful way. I like pushing myself and taking up new challenges.

If you read this far, thank the author to show them you care. Say Thanks

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

DEV Community

DEV Community

AbdulKarim

Posted on Oct 29, 2023

How C-Pointers Works: A Step-by-Step Beginner's Tutorial

In this comprehensive C Pointers tutorial, my primary goal is to guide you through the fundamentals of C pointers from the ground up. By the end of this tutorial, you will have gained an in-depth understanding of the following fundamental topics:

  • What is a Pointer?
  • How Data is Stored in Memory?
  • Storing Memory Addresses using Pointers

Accessing Data through Pointers

  • Pointer Arithmetic
  • Pointer to Pointer (Double Pointers)
  • Passing Pointers as Function Arguments

Arrays of Pointers

Null pointers, prerequisite:.

To grasp pointers effectively, you should be comfortable with basic C programming concepts, including variables, data types, functions, loops, and conditional statements. This familiarity with C programming forms the foundation for understanding how pointers work within the language. Once you have a solid grasp of these fundamental concepts, you can confidently delve into the intricacies of C pointers.

What is a pointer?

A pointer serves as a reference that holds the memory location of another variable. This memory address allows us to access the value stored at that location in the memory. You can think of a pointer as a way to reference or point to the location where data is stored in your computer's memory

Pointers can be a challenging concept for beginners to grasp, but in this tutorial, I'll explain them using real-life analogies to make the concept clearer. However, Before delving into pointers and their workings, it's important to understand the concept of a memory address.

A memory address is a unique identifier that points to a specific location in a computer's memory. Think of it like a street address for data stored in your computer's RAM (Random Access Memory). Just as a street address tells you where a particular house is located in the physical world, a memory address tells the computer where a specific piece of information or data is stored in its memory.

Take a look at the image below for a better understanding:

Block of memory

In this illustration, each block represents one byte of memory. It's important to note that every byte of memory has a unique address. To make it easier to understand, I've represented the addresses in decimal notation, but computers actually store these addresses using hexadecimal values. Hexadecimal is a base-16 numbering system commonly used in computing to represent memory addresses and other low-level data. It's essential to be aware of this representation when working with memory-related concepts in computer programming

How data is stored in the memory:

Every piece of data in your computer, whether it's a number, a character, or a program instruction, is stored at a specific memory address. The amount of space reserved for each data type can vary, and it is typically measured in bytes (where 1 byte equals 8 bits, with each bit representing either 0 or 1). The specific sizes of data types also depend on the computer architecture you are using. For instance, on most 64-bit Linux machines, you'll find the following typical sizes for common data types: char = 1 byte int = 4 bytes float = 4 bytes double = 8 bytes These sizes define how much memory each data type occupies and are crucial for memory management and efficient data representation in computer systems.

You can use the sizeof operator to determine the size of data types on your computer. example:

In this example: sizeof(char) returns the size of the char data type in bytes. sizeof(int) returns the size of the int data type in bytes. sizeof(float) returns the size of the float data type in bytes. sizeof(double) returns the size of the double data type in bytes. When you run this code, it will print the sizes of these data types on your specific computer, allowing you to see the actual sizes used by your system.

When you declare a variable, the computer allocates a specific amount of memory space corresponding to the chosen data type. For instance, when you declare a variable of type char, the computer reserves 1 byte of memory because the size of the 'char' data type is conventionally 1 byte.

address of char n

In this example, we declare a variable n of type char without assigning it a specific value. The memory address allocated for the n variable is 106 . This address, 106 , is where the computer will store the char variable n, but since we haven't assigned it a value yet, the content of this memory location may initially contain an unpredictable or uninitialized value.

When we assign the value 'C' to the variable n, the character 'C' is stored in the memory location associated with the variable n. When we assign the value 'C' to the variable n, the character 'C' is stored in the memory location associated with the variable n.

address of cahr n = c

As mentioned earlier, a byte can only store numerical values. When we store the letter 'C' in a byte, the byte actually holds the ASCII code for 'C,' which is 67. In computer memory, characters are represented using their corresponding ASCII codes. So, in memory, the character 'C' is stored as the numerical value 67. Here's how it looks in memory

Ascii code of c

Since integers are typically stored within four bytes of memory, let's consider the same example with an int variable. In this scenario, the memory structure would appear as follows:

add. of int t

In this example, the memory address where the variable t is stored is 121. An int variable like “t” typically uses four consecutive memory addresses, such as 121, 122, 123, and 124. The starting address, in this case, 121, represents the location of the first byte of the int, and the subsequent addresses sequentially represent the following bytes that collectively store the complete int value.

If you want to know the memory address of a variable in a program, you can use the 'address of' unary operator, often denoted as the '&' operator. This operator allows you to access the specific memory location where a variable is stored.

When you run the following program on your computer: It will provide you with specific memory addresses for the variables c and n. However, each time you rerun the program, it might allocate new memory addresses for these variables. It's important to understand that while you can determine the memory address of a variable using the & operator, the exact memory location where a variable is stored is typically managed by the system and the compiler. As a programmer, you cannot directly control or assign a specific memory location for a variable. Instead, memory allocation and management are tasks handled by the system and the compiler.

Storing memory address using pointers

As mentioned earlier, a pointer is a variable that stores the memory address of another variable. This memory address allows us to access the value stored at that location in memory. You can think of a pointer as a way to reference or point to the location where data is stored in your computer's memory.

Now, let's begin by declaring and initializing pointers. This step is essential because it sets up the pointer to hold a specific memory address, enabling us to interact with the data stored at that location.

Declaring Pointers: To declare a pointer, you specify the data type it points to, followed by an asterisk (*), and then the pointer's name. For example:

Here, we've declared a pointer named ptr that can point to integers.

Memory of Declaring an integer pointer

The size of pointers on 64-bit systems is usually 8 bytes (64 bits). To determine the pointer size on your system, you can use the sizeof operator:

Initializing Pointers: Once you've declared a pointer, you typically initialize it with the memory address it should point to. Once again, To obtain the memory address of a variable, you can employ the address-of operator (&). For instance:

In this program:

We declare an integer variable x and initialize it with the value 10. This line creates a variable x in memory and assigns the value 10 to it.

ptr

We declare an integer pointer ptr using the int *ptr syntax. This line tells the compiler that ptr will be used to store the memory address of an integer variable.

pointrt to ptr

We initialize the pointer ptr with the memory address of the variable x . This is achieved with the line ptr = &x; . The & operator retrieves the memory address of x, and this address is stored in the pointer ptr .

address of variable x

Dereferencing Pointers: To access the data that a pointer is pointing to, you need to dereference the pointer. Dereferencing a pointer means accessing the value stored at the memory address that the pointer points to. In C, you can think of pointers as variables that store memory addresses rather than actual values. To get the actual value (data) stored at that memory address, you need to dereference the pointer.

Dereferencing is done using the asterisk (*) operator. Here's an example:

It looks like this in the memory: int x = 10; variable 'x' stores the value 10:

var X

int *ptr = &x; Now, the pointer 'ptr' point to the address of 'x':

Pointer to X

int value = *ptr; Dereference 'ptr' to get the value stored at the address it points to:

pointer value is 10

Reading and Modifying Data: Pointers allow you to not only read but also modify data indirectly:

Note: The asterisk is a versatile symbol with different meanings depending on where it's used in your C program, for example: Declaration: When used during variable declaration, the asterisk (*) indicates that a variable is a pointer to a specific data type. For example: int *ptr; declares 'ptr' as a pointer to an integer.

Dereferencing: Inside your code, the asterisk (*) in front of a pointer variable is used to access the value stored at the memory address pointed to by the pointer. For example: int value = *ptr; retrieves the value at the address 'ptr' points to.

Pointer Arithmetic:

Pointer arithmetic is the practice of performing mathematical operations on pointers in C. This allows you to navigate through arrays, structures, and dynamically allocated memory. You can increment or decrement pointers, add or subtract integers from them, and compare them. It's a powerful tool for efficient data manipulation, but it should be used carefully to avoid memory-related issues.

Incrementing a Pointer:

Now, this program is how it looks in the memory: int arr[4] = {10, 20, 30, 40};

int arr

This behavior is a key aspect of pointer arithmetic. When you add an integer to a pointer, it moves to the memory location of the element at the specified index, allowing you to efficiently access and manipulate elements within the array. It's worth noting that you can use pointer arithmetic to access elements in any position within the array, making it a powerful technique for working with arrays of data. Now, let's print the memory addresses of the elements in the array from our previous program.

If you observe the last two digits of the first address is 40, and the second one is 44. You might be wondering why it's not 40 and 41. This is because we're working with an integer array, and in most systems, the size of an int data type is 4 bytes. Therefore, the addresses are incremented in steps of 4. The first address shows 40, the second 44, and the third one 48

Decrementing a Pointer Decrement (--) a pointer variable, which makes it point to the previous element in an array. For example, ptr-- moves it to the previous one. For example:

Explanation:

We have an integer array arr with 5 elements, and we initialize a pointer ptr to point to the fourth element (value 40) using &arr[3].

Then, we decrement the pointer ptr by one with the statement ptr--. This moves the pointer to the previous memory location, which now points to the third element (value 30).

Finally, we print the value pointed to by the decremented pointer using *ptr, which gives us the value 30.

In this program, we demonstrate how decrementing a pointer moves it to the previous memory location in the array, allowing you to access and manipulate the previous element.

Pointer to pointer

Pointers to pointers, or double pointers, are variables that store the address of another pointer. In essence, they add another level of indirection. These are commonly used when you need to modify the pointer itself or work with multi-dimensional arrays.

To declare and initialize a pointer to a pointer, you need to add an extra asterisk (*) compared to a regular pointer. Let's go through an example:

In this example, ptr2 is a pointer to a pointer. It points to the memory location where the address of x is stored (which is ptr1 ).

pointer to poiter

The below program will show you how to print the value of x through pointer to pointer

In this program, we first explain that it prints the value of x using a regular variable, a pointer, and a pointer to a pointer. We then print the memory addresses of x , ptr1 , and ptr2 .

Passing Pointers as Function Arguments:

In C, you can pass pointers as function arguments. This allows you to manipulate the original data directly, as opposed to working with a copy of the data, as you would with regular variables. Here's how it works:

How to Declare and Define Functions that Take Pointer Arguments: In your function declaration and definition, you specify that you're passing a pointer by using the * operator after the data type. For example:

In the above function, we declare ptr as a pointer to an integer. This means it can store the memory address of an integer variable.

Why Would You Pass Pointers to Functions?

Passing pointers to functions allows you to:

  • Modify the original data directly within the function.
  • Avoid making a copy of the data, which can be more memory-efficient.
  • Share data between different parts of your program efficiently.

This concept is especially important when working with large data structures or when you need to return multiple values from a function.

Call by Value vs. Call by Reference:

Understanding how data is passed to functions is crucial when working with pointers. there are two common ways that data can be passed to functions: call by value and call by reference.

Call by Value:

When you pass data by value, a copy of the original data is created inside the function. Any modifications to this copy do not affect the original data outside of the function. This is the default behavior for most data types when you don't use pointers.

Call by Reference (Using Pointers):

When you pass data by reference, you're actually passing a pointer to the original data's memory location. This means any changes made within the function will directly affect the original data outside the function. This is achieved by passing pointers as function arguments, making it call by reference. Using pointers as function arguments allows you to achieve call by reference behavior, which is particularly useful when you want to modify the original data inside a function and have those changes reflected outside the function.

Let's dive into some code examples to illustrate how pointers work as function arguments. We'll start with a simple example to demonstrate passing a pointer to a function and modifying the original data.

Consider this example:

In this code, we define a function modifyValue that takes a pointer to an integer. We pass the address of the variable num to this function, and it doubles the value stored in num directly.

This is a simple demonstration of passing a pointer to modify a variable's value. Pointers allow you to work with the original data efficiently.

An array of pointers is essentially an array where each element is a pointer. These pointers can point to different data types (int, char, etc.), providing flexibility and efficiency in managing memory.

How to Declare an Array of Pointers? To declare an array of pointers, you specify the type of data the pointers will point to, followed by square brackets to indicate it's an array, and then the variable name. For example:

Initializing an Array of Pointers You can initialize an array of pointers to each element to point to a specific value, For example:

How to Access Elements Through an Array of Pointers? To access elements through an array of pointers, you can use the pointer notation. For example:

This program demonstrates how to access and print the values pointed to by the pointers in the array.

A NULL pointer is a pointer that lacks a reference to a valid memory location. It's typically used to indicate that a pointer doesn't have a specific memory address assigned, often serving as a placeholder or default value for pointers.

Here's a code example that demonstrates the use of a NULL pointer:

In this example, we declare a pointer ptr and explicitly initialize it with the value NULL. We then use an if statement to check if the pointer is NULL. Since it is, the program will print "The pointer is NULL." This illustrates how NULL pointers are commonly used to check if a pointer has been initialized or assigned a valid memory address.

conclusion:

You've embarked on a comprehensive journey through the intricacies of C pointers. You've learned how pointers store memory addresses, enable data access, facilitate pointer arithmetic, and how they can be used with arrays and functions. Additionally, you've explored the significance of NULL pointers.

By completing this tutorial, you've equipped yourself with a robust understanding of pointers in C. You can now confidently navigate memory, manipulate data efficiently, and harness the power of pointers in your programming projects. These skills will be invaluable as you advance in your coding endeavors. Congratulations on your accomplishment, and keep coding with confidence!

Reference: C - Pointers - Tutorials Point

Pointers in C: A One-Stop Solution for Using C Pointers - simplilearn

Top comments (3)

pic

Templates let you quickly answer FAQs or store snippets for re-use.

imperiald profile image

  • Joined Jan 7, 2024

Love your way to write articles, could you add an article for, .o files, .h files, lists and makefile? Thank you in advance!

cocomelonjuice profile image

  • Joined Nov 4, 2023

Great post. Thank you so much for this.

koderkareem profile image

Thank you for your kind words! I'm thrilled to hear that you enjoyed the article. Your feedback means a lot to me. If you have any questions or if there's a specific topic you'd like to see in future posts, feel free to let me know. Thanks again for your support

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink .

Hide child comments as well

For further actions, you may consider blocking this person and/or reporting abuse

furkangozukara profile image

Stable Cascade Prompt Following Is Amazing — This Model Has Huge Potential — High Resolutions Uses Lesser VRAM

Furkan Gözükara - Feb 14

dimuthnilanjana profile image

UI/UX for Beginners

Dimuth Nilanjana - Feb 14

devendra_2806 profile image

JavaScript Loops: A Beginner's Guide

Devendra Devendra - Feb 18

sre_panchanan profile image

OWASP API6:2023 Unrestricted Access to Sensitive Business Flows 🔐👤💔

Panchanan Panigrahi - Feb 14

Once suspended, koderkareem will not be able to comment or publish posts until their suspension is removed.

Once unsuspended, koderkareem will be able to comment and publish posts again.

Once unpublished, all posts by koderkareem will become hidden and only accessible to themselves.

If koderkareem is not suspended, they can still re-publish their posts from their dashboard.

Once unpublished, this post will become invisible to the public and only accessible to AbdulKarim.

They can still re-publish the post if they are not suspended.

Thanks for keeping DEV Community safe. Here is what you can do to flag koderkareem:

koderkareem consistently posts content that violates DEV Community's code of conduct because it is harassing, offensive or spammy.

Unflagging koderkareem will restore default visibility to their posts.

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Codeforwin

Pointers in C – Declare, initialize and use

Pointers are the heart of C programming. It is the most distinct feature of C, which provides power and flexibility to C. Pointers separates C from other programming languages.

C programmers make extensive use of pointers, because of their numerous benefits. Below are some advantages of pointers.

  • Pointers are more efficient in handling arrays and structures.
  • Pointers are used to return multiple values from a function.
  • We use pointers to get reference of a variable or function.
  • Pointer allows dynamic memory allocation (creation of variables at runtime) in C. Which undoubtedly is the biggest advantage of pointers.
  • Pointers increases execution speed of program.

Pointers are closely related to low level memory operations. Hence, let us first understand memory in contrast to C programming.

Understanding memory

Computer memory ( RAM ) is a collection of contiguous block of bytes. Where individual block is called as cell (memory cell). Each cell has a unique numeric address (also known as physical memory address) associated with it. These addresses starts from zero and runs up to maximum memory size (in bytes).

For example, memory location of a 64KB RAM starts from 0 and ends to 65536 (or 0x10000) bytes.

Memory representation

Before I formally introduce pointers let us first see what happens during a variable definition. Consider the statement int num = 10;

  • For the above statement, the C compiler allocates memory capable to store an integer. Let say memory is allocated at address 0x1200 .
  • After memory allocation , the C compiler defines a label (variable name) to access the memory location. The label is mapped to the allocated memory.
  • Finally, the constant 10 is stored at 0x1200 . Whenever you refer num inside your program, internally C refers to the memory location of num .

What is a pointer?

A pointer is a variable that stores memory address. If it is a variable, it must have a valid C data type . Yes, every pointer variable has a data type associated with it. Which means an integer pointer can hold only integer variable addresses.

Note: We never say pointer stores or holds a memory location. Instead, we say pointer points to a memory location. So from now always use the language pointer points to a memory location.

Reference operator &

Because we are dealing with memory addresses, we must know how to get memory address of a variable. We use unary & (reference of) operator to get memory address of a variable. Reference operator is also known as address of operator .

Read more about operators in C programming .

Syntax to use reference of operator

Example program to use reference operator.

Note: Output of above program may vary on your machine.

Dereference operator *

Once you have a memory address, you must be willing to get value stored at that memory address, for that we need to dereference the memory address.

Dereferencing is the process of retrieving value at memory location pointed by a pointer. We use unary * dereference operator to get value pointed by a memory address. Dereference operator is also known as indirection operator .

Syntax to use dereference operator

Example program to use dereference operator, how to declare pointer variable.

Once you got basics of memory addresses, reference and dereference operator. Let us declare our first pointer variable.

Pointer variable declaration follows almost similar syntax as of normal variable.

Syntax to declare pointer variable

  • data-type is a valid C data type .
  • * symbol specifies it is a pointer variable. You must prefix * before variable name to declare it as a pointer.
  • pointer-variable-name is a valid C identifier i.e. the name of pointer variable.

Example to declare pointer variable

In above example I declared an integer pointer.

How to initialize pointer variable

There are two ways to initialize a pointer variable. You can use reference operator & to get memory location of a variable or you can also directly assign one pointer variable to other pointer variable.

Examples to initialize pointer variable

How pointers are stored in memory.

You got a basic picture of pointer working. Let us take a closer look on how pointer variables are stored in memory. Consider the following statements

Pointer memory representation

Example program to use pointers

Write a C program to demonstrate the use of pointers in C programming.

Note: %x format specifier is used to print hexadecimal representation of a decimal .

Output –

Note: Output of above program may differ on your system.

Working of above program

  • int *ptr = # declares an integer pointer that points at num .
  • The first two printf() in line 12 and 13 are straightforward. First prints value of num and other prints memory address of num .
  • printf("Value of ptr = %x \n", ptr); prints the value stored at ptr i.e. memory address of num . Hence, the statement prints memory address of num .

Don’t confuse with address of ptr and address pointed by ptr . First ptr is a variable so it will have a memory address which is retrieved using &ptr . And since it is a pointer variable hence it stores memory address which is retrieved using ptr .

  • printf("Value pointed by ptr = %d \n\n", *ptr); , here * dereferences value pointed by ptr and prints the value at memory location pointed by ptr .
  • Next, we made some changes to num i.e. num=10 . After changes printf("Value of num = %d \n", num); prints 10.
  • Since we made changes to our original variable num , hence changes are reflected back to pointer that points to the num . *ptr in line 23, dereferences value pointed by ptr i.e. 10.
  • *ptr = 100; says assign 100 to memory location pointed by ptr . Which means, assign 100 to num indirectly.
  • Since, we again modified the value of num using *ptr = 100 . Hence, num and *ptr in line 28 and 29 will evaluate to 100.

Recommended examples to practice

  • Program to demonstrate use of pointers.
  • Program to add two numbers using pointers.
  • Program to swap two numbers using pointers.
  • 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++ Programming Language

C++ Overview

  • Introduction to C++ Programming Language
  • Features of C++
  • History of C++
  • Interesting Facts about C++
  • Setting up C++ Development Environment
  • Difference between C and C++
  • Writing First C++ Program - Hello World Example
  • C++ Basic Syntax
  • C++ Comments
  • Tokens in C
  • C++ Keywords
  • Difference between Keyword and Identifier

C++ Variables and Constants

  • C++ Variables
  • Constants in C
  • Scope of Variables in C++
  • Storage Classes in C++ with Examples
  • Static Keyword in C++

C++ Data Types and Literals

  • Literals in C
  • Derived Data Types in C++
  • User Defined Data Types in C++
  • Data Type Ranges and their macros in C++
  • C++ Type Modifiers
  • Type Conversion in C++
  • Casting Operators in C++

C++ Operators

  • Operators in C++
  • C++ Arithmetic Operators
  • Unary operators in C
  • Bitwise Operators in C
  • Assignment Operators in C
  • C++ sizeof Operator
  • Scope resolution operator in C++
  • Basic Input / Output in C++
  • cout in C++
  • cerr - Standard Error Stream Object in C++
  • Manipulators in C++ with Examples

C++ Control Statements

  • Decision Making in C (if , if..else, Nested if, if-else-if )
  • C++ if Statement
  • C++ if else Statement
  • C++ if else if Ladder
  • Switch Statement in C++
  • Jump statements in C++
  • for Loop in C++
  • Range-based for loop in C++
  • C++ While Loop
  • C++ Do/While Loop

C++ Functions

  • Functions in C++
  • return statement in C++ with Examples
  • Parameter Passing Techniques in C
  • Difference Between Call by Value and Call by Reference in C
  • Default Arguments in C++
  • Inline Functions in C++
  • Lambda expression in C++

C++ Pointers and References

  • Pointers and References in C++
  • Dangling, Void , Null and Wild Pointers in C
  • Applications of Pointers in C
  • Understanding nullptr in C++
  • References in C++
  • Can References Refer to Invalid Location in C++?
  • Pointers vs References in C++
  • Passing By Pointer vs Passing By Reference in C++
  • When do we pass arguments by pointer?
  • Variable Length Arrays (VLAs) in C
  • Pointer to an Array | Array Pointer
  • How to print size of array parameter in C++?
  • Pass Array to Functions in C
  • What is Array Decay in C++? How can it be prevented?

C++ Strings

  • Strings in C++
  • std::string class in C++
  • Array of Strings in C++ - 5 Different Ways to Create
  • String Concatenation in C++
  • Tokenizing a string in C++
  • Substring in C++

C++ Structures and Unions

  • Structures, Unions and Enumerations in C++
  • Structures in C++
  • C++ - Pointer to Structure
  • Self Referential Structures
  • Difference Between C Structures and C++ Structures
  • Enumeration in C++
  • typedef in C++
  • Array of Structures vs Array within a Structure in C

C++ Dynamic Memory Management

  • Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()
  • new and delete Operators in C++ For Dynamic Memory
  • new vs malloc() and free() vs delete in C++
  • What is Memory Leak? How can we avoid?
  • Difference between Static and Dynamic Memory Allocation in C

C++ Object-Oriented Programming

  • Object Oriented Programming in C++
  • C++ Classes and Objects
  • Access Modifiers in C++
  • Friend Class and Function in C++
  • Constructors in C++
  • Default Constructors in C++
  • Copy Constructor in C++
  • Destructors in C++
  • Private Destructor in C++
  • When is a Copy Constructor Called in C++?
  • Shallow Copy and Deep Copy in C++
  • When Should We Write Our Own Copy Constructor in C++?
  • Does C++ compiler create default constructor when we write our own?
  • C++ Static Data Members
  • Static Member Function in C++
  • 'this' pointer in C++
  • Scope Resolution Operator vs this pointer in C++
  • Local Classes in C++
  • Nested Classes in C++
  • Enum Classes in C++ and Their Advantage over Enum DataType
  • Difference Between Structure and Class in C++
  • Why C++ is partially Object Oriented Language?

C++ Encapsulation and Abstraction

  • Encapsulation in C++
  • Abstraction in C++
  • Difference between Abstraction and Encapsulation in C++
  • C++ Polymorphism
  • Function Overriding in C++
  • Virtual Functions and Runtime Polymorphism in C++
  • Difference between Inheritance and Polymorphism

C++ Function Overloading

  • Function Overloading in C++
  • Constructor Overloading in C++
  • Functions that cannot be overloaded in C++
  • Function overloading and const keyword
  • Function Overloading and Return Type in C++
  • Function Overloading and float in C++
  • C++ Function Overloading and Default Arguments
  • Can main() be overloaded in C++?
  • Function Overloading vs Function Overriding in C++
  • Advantages and Disadvantages of Function Overloading in C++

C++ Operator Overloading

  • Operator Overloading in C++
  • Types of Operator Overloading in C++
  • Functors in C++
  • What are the Operators that Can be and Cannot be Overloaded in C++?

C++ Inheritance

  • Inheritance in C++
  • C++ Inheritance Access
  • Multiple Inheritance in C++
  • C++ Hierarchical Inheritance
  • C++ Multilevel Inheritance
  • Constructor in Multiple Inheritance in C++
  • Inheritance and Friendship in C++
  • Does overloading work with Inheritance?

C++ Virtual Functions

  • Virtual Function in C++
  • Virtual Functions in Derived Classes in C++
  • Default Arguments and Virtual Function in C++
  • Can Virtual Functions be Inlined in C++?
  • Virtual Destructor
  • Advanced C++ | Virtual Constructor
  • Advanced C++ | Virtual Copy Constructor
  • Pure Virtual Functions and Abstract Classes in C++
  • Pure Virtual Destructor in C++
  • Can Static Functions Be Virtual in C++?
  • RTTI (Run-Time Type Information) in C++
  • Can Virtual Functions be Private in C++?
  • Exception Handling in C++
  • Exception Handling using classes in C++
  • Stack Unwinding in C++
  • User-defined Custom Exception with class in C++

C++ Files and Streams

  • File Handling through C++ Classes
  • I/O Redirection in C++

C++ Templates

  • Templates in C++ with Examples
  • Template Specialization in C++
  • Using Keyword in C++ STL

C++ Standard Template Library (STL)

  • The C++ Standard Template Library (STL)
  • Containers in C++ STL (Standard Template Library)
  • Introduction to Iterators in C++
  • Algorithm Library | C++ Magicians STL Algorithm

C++ Preprocessors

  • C Preprocessors
  • C Preprocessor Directives
  • #include in C
  • Difference between Preprocessor Directives and Function Templates in C++

C++ Namespace

  • Namespace in C++ | Set 1 (Introduction)
  • namespace in C++ | Set 2 (Extending namespace and Unnamed namespace)
  • Namespace in C++ | Set 3 (Accessing, creating header, nesting and aliasing)
  • C++ Inline Namespaces and Usage of the "using" Directive Inside Namespaces

Advanced C++

  • Multithreading in C++
  • Smart Pointers in C++
  • auto_ptr vs unique_ptr vs shared_ptr vs weak_ptr in C++
  • Type of 'this' Pointer in C++
  • "delete this" in C++
  • Passing a Function as a Parameter in C++
  • Signal Handling in C++
  • Generics in C++
  • Difference between C++ and Objective C
  • Write a C program that won't compile in C++
  • Write a program that produces different results in C and C++
  • How does 'void*' differ in C and C++?
  • Type Difference of Character Literals in C and C++
  • Cin-Cout vs Scanf-Printf

C++ vs Java

  • Similarities and Difference between Java and C++
  • Comparison of Inheritance in C++ and Java
  • How Does Default Virtual Behavior Differ in C++ and Java?
  • Comparison of Exception Handling in C++ and Java
  • Foreach in C++ and Java
  • Templates in C++ vs Generics in Java
  • Floating Point Operations & Associativity in C, C++ and Java

Competitive Programming in C++

  • Competitive Programming - A Complete Guide
  • C++ tricks for competitive programming (for C++ 11)
  • Writing C/C++ code efficiently in Competitive programming
  • Why C++ is best for Competitive Programming?
  • Test Case Generation | Set 1 (Random Numbers, Arrays and Matrices)
  • Fast I/O for Competitive Programming
  • Setting up Sublime Text for C++ Competitive Programming Environment
  • How to setup Competitive Programming in Visual Studio Code for C++
  • Which C++ libraries are useful for competitive programming?
  • Common mistakes to be avoided in Competitive Programming in C++ | Beginners
  • C++ Interview Questions and Answers (2024)
  • Top C++ STL Interview Questions and Answers
  • 30 OOPs Interview Questions and Answers (2024)
  • Top C++ Exception Handling Interview Questions and Answers
  • C++ Programming Examples

Pointers are symbolic representations of addresses. They enable programs to simulate call-by-reference as well as to create and manipulate dynamic data structures. Iterating over elements in arrays or other data structures is one of the main use of pointers. 

The address of the variable you’re working with is assigned to the pointer variable that points to the same data type (such as an int or string).

How pointer works in C++

How to use a pointer?

  • Define a pointer variable
  • Assigning the address of a variable to a pointer using the unary operator (&) which returns the address of that variable.
  • Accessing the value stored in the address using unary operator (*) which returns the value of the variable located at the address specified by its operand.

The reason we associate data type with a pointer is that it knows how many bytes the data is stored in . When we increment a pointer, we increase the pointer by the size of the data type to which it points.

Pointers in C++

References and Pointers

There are 3 ways to pass C++ arguments to a function:

  • Call-By-Value
  • Call-By-Reference with a Pointer Argument
  • Call-By-Reference with a Reference Argument

In C++, by default arguments are passed by value and the changes made in the called function will not reflect in the passed variable. The changes are made into a clone made by the called function. If wish to modify the original copy directly (especially in passing huge object or array) and/or avoid the overhead of cloning, we use pass-by-reference. Pass-by-Reference with Reference Arguments does not require any clumsy syntax for referencing and dereferencing.

  • Function pointers in C
  • Pointer to a Function

Array Name as Pointers

An array name contains the address of the first element of the array which acts like a constant pointer. It means, the address stored in the array name can’t be changed. For example, if we have an array named val then val and &val[0] can be used interchangeably. 

Representation of data in memory

 If pointer ptr is sent to a function as an argument, the array val can be accessed in a similar fashion. Pointer vs Array

Pointer Expressions and Pointer Arithmetic

A limited set of arithmetic operations can be performed on pointers which are:

  • incremented ( ++ )
  • decremented ( — )
  • an integer may be added to a pointer ( + or += )
  • an integer may be subtracted from a pointer ( – or -= )
  • difference between two pointers (p1-p2)

( Note: Pointer arithmetic is meaningless unless performed on an array.) 

Representation of data in memory

Advanced Pointer Notation

Consider pointer notation for the two-dimensional numeric arrays. consider the following declaration

In general, nums[ i ][ j ] is equivalent to *(*(nums+i)+j)  

Pointer notation in C++

Pointers and String literals

String literals are arrays containing null-terminated character sequences. String literals are arrays of type character plus terminating null-character, with each of the elements being of type const char (as characters of string can’t be modified).

This declares an array with the literal representation for “geek”, and then a pointer to its first element is assigned to ptr. If we imagine that “geek” is stored at the memory locations that start at address 1800, we can represent the previous declaration as: 

Pointers and String Literals

As pointers and arrays behave in the same way in expressions, ptr can be used to access the characters of a string literal. For example:

Here, both x and y contain k stored at 1803 (1800+3).

Pointers to pointers

In C++, we can create a pointer to a pointer that in turn may point to data or another pointer. The syntax simply requires the unary operator (*) for each level of indirection while declaring the pointer.

Here b points to a char that stores ‘g’ and c points to the pointer b.

Void Pointers

This is a special type of pointer available in C++ which represents the absence of type. Void pointers are pointers that point to a value that has no type (and thus also an undetermined length and undetermined dereferencing properties). This means that void pointers have great flexibility as they can point to any data type. There is a payoff for this flexibility. These pointers cannot be directly dereferenced. They have to be first transformed into some other pointer type that points to a concrete data type before being dereferenced. 

Invalid pointers

A pointer should point to a valid address but not necessarily to valid elements (like for arrays). These are called invalid pointers. Uninitialized pointers are also invalid pointers.

Here, ptr1 is uninitialized so it becomes an invalid pointer and ptr2 is out of bounds of arr so it also becomes an invalid pointer. (Note: invalid pointers do not necessarily raise compile errors)

NULL Pointers

A null pointer is a pointer that point nowhere and not just an invalid address. Following are 2 methods to assign a pointer as NULL;

Advantages of Pointers

  • Pointers reduce the code and improve performance. They are used to retrieve strings, trees, arrays, structures, and functions.
  • Pointers allow us to return multiple values from functions.
  • In addition to this, pointers allow us to access a memory location in the computer’s memory.

Related Articles:

  • Opaque Pointer
  • Near, Far and huge Pointers
  • Pointer Basics
  • Advanced Pointer

Please Login to comment...

  • cpp-pointer
  • BabisSarantoglou
  • kamleshjoshi18

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

What happens if Fulton County DA Fani Willis is disqualified from the Trump racketeering case?

If a Georgia judge signs off on a bid to disqualify Fulton County District Attorney Fani Willis from her racketeering case against former President Donald Trump and numerous co-defendants, it could delay any trial until well after the 2024 election — and possibly scuttle the charges altogether, legal experts told NBC News.

For a new prosecutor to take over the sprawling 15-defendant case would be a “massive undertaking,” said Amy Lee Copeland, a defense lawyer and former federal prosecutor in Georgia, adding that the theoretical new prosecutor could decide to amend the charges or even “decide not to pursue it.”

Fulton County Superior Court Judge Scott McAfee held an evidentiary hearing on Thursday and Friday over misconduct allegations that have been aimed at Willis and the special prosecutor she appointed to the case, Nathan Wade. Michael Roman, one of Trump’s co-defendants, alleged the pair engaged in an “improper,  clandestine personal relationship ” and “have enriched themselves off this case.”

Willis and Wade have denied any wrongdoing. McAfee has not yet ruled on the motion, but said earlier this week, “Because I think it’s possible that the facts alleged by the defendant could result in disqualification, I think an evidentiary hearing must occur to establish the record on those core allegations.”

If McAfee were to grant Roman’s motion, it would grind the case — which currently does not have a scheduled trial date — to a halt. If Willis were to be disqualified, her entire office would be as well, Copeland said.

Under a 2022 Georgia law , when a district attorney is disqualified, the case is referred to the executive director of the Prosecuting Attorneys’ Council of Georgia, who is tasked with finding another prosecutor for the case.

“If Judge McAfee signs an order disqualifying DA Willis, it becomes incumbent upon me to select a special prosecutor and appoint a special prosecutor,” the council’s executive director, Pete Skandalakis , told NBC News.

Skandalakis, a former district attorney, said his office would “begin by looking for who has the resources and capability — not only personnel and expertise but also financial” to handle such a case.

“The bigger the case, the more expense is involved,” he said. He would also be mindful of “geography — who’s closest to the site” — and “who has an extremely high caseload and who has a light caseload.”

“You’re looking for someone who’s a neutral arbiter and can make decisions based upon the evidence,” and ideally someone who wants to take the case, Skandalakis said.

“As I read the statute, a DA cannot refuse an appointment, but it’s best to find somebody willing to take on the assignment,” he said.

In addition to various DA’s offices, Skandalakis could choose to keep the case himself, assign it to the state attorney general’s office or appoint a private lawyer as special counsel, but he said financial constraints make the last option unlikely.

“If I were to appoint a private lawyer, the statute constrains me to pay the hourly rate of an elected district attorney, which is about $70 an hour, and I can’t pay for him or her to hire an investigator” or other help, he said.

He said whoever takes over the case would be able to use the investigative work that’s already been completed by the DA’s office, but they’d also have the ability to do additional investigative work and to use — or discard — some or all of Willis’ indictment.

“You have to look at the case as if you’re starting from scratch,” he said.

Asked how politics could come into play in his potential search, Skandalakis, a Republican, said, “I think it would be disingenuous to say politics isn’t a part of any process, but I’m still looking for someone who could be neutral and could make their decision based on the evidence that’s available.”

J. Tom Morgan, a professor at Western Carolina University and a former DeKalb County district attorney, said any new prosecutor would likely “skinny” the case down to make it “a more manageable, triable case.” The current indictment is “a pig’s breakfast, a total slop,” he said.

But, he added, it would take time for a new prosecutor to get up to speed and then trim it down. “Ms. Willis’ office has been on this case for two and a half years,” he said.

There could be other delays as well. If Willis were to appeal a disqualification ruling, Skandalakis said he would hold off on appointing a new prosecutor until the appeal was decided.

“If she wins the appeal, it wouldn’t make sense for me to appoint somebody and then it goes back to her, so we’d have to wait,” he said.

The disqualification statute does not set out a time table to act. Skandalakis said there would be no statute of limitation issues since the defendants have already been indicted.

Copeland said any lengthy delays could trigger individual speedy trial claims.

She added that history doesn’t indicate that the process of finding a new DA will move swiftly.

In July of 2022, Willis was disqualified from investigating Burt Jones , then a state senator who was running for lieutenant governor, as part of the Trump probe. The disqualification came after she hosted a fundraiser backing a Democratic candidate running for the same job.

That probe was then sent to the Prosecuting Attorneys’ Council, which has yet to select a prosecutor to continue the investigation into the now-lieutenant governor. “This wouldn’t be faster,” Copeland said.

Skandalakis said that case has different issues and court-ordered constraints.

“The two are completely different animals,” he said.

set pointer to another pointer c

Dareh Gregorian is a politics reporter for NBC News.

IMAGES

  1. C Pointer to Pointer (Theory & Example)

    set pointer to another pointer c

  2. C Pointers

    set pointer to another pointer c

  3. C

    set pointer to another pointer c

  4. Pointer to Pointer in C Programming Language Video Tutorials for Beginners

    set pointer to another pointer c

  5. c

    set pointer to another pointer c

  6. Pointer to pointer in c with example

    set pointer to another pointer c

VIDEO

  1. Pointers in C Language Explained

  2. 14. this pointer in c++

  3. Part-1

  4. Pointers to Pointers

  5. Extra Problems 1 Pointers double pointers tracing inside function

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

COMMENTS

  1. C setting a pointer to another pointer and freeing

    4 Answers Sorted by: 10 When you do int *p1 = malloc (sizeof (int)*10); you have something like +----+ +---------------------------------+ | p1 | --> | Memory enough for 10 int values | +----+ +---------------------------------+ Then when you do int *p2 = p1; you have something like

  2. C

    The pointer to a pointer in C is used when we want to store the address of another 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.

  3. 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.

  4. C

    C - Pointer to Pointer. A pointer to a pointer is a form of multiple indirection, or a chain of pointers. Normally, a pointer contains the address of a variable. When we define a pointer to a pointer, the first pointer contains the address of the second pointer, which points to the location that contains the actual value as shown below.

  5. C Pointers

    1. Pointer Declaration In pointer declaration, we only declare the pointer but do not initialize it. To declare a pointer, we use the ( * ) dereference operator before its name. Example int *ptr; The pointer declared here will point to some random memory address as it is not initialized. Such pointers are called wild pointers. 2.

  6. C Pointers (With Examples)

    To get the value of the thing pointed by the pointers, we use the * operator. For example: int* pc, c; c = 5; pc = &c; printf("%d", *pc); // Output: 5 Here, the address of c is assigned to the pc pointer. To get the value stored in that address, we used *pc. Note: In the above example, pc is a pointer, not *pc.

  7. Pointer Basics

    The dereference operation on a pointer only works if the pointer has a pointee -- the pointee must be allocated and the pointer must be set to point to it. The most common error in pointer code is forgetting to set up the pointee. The most common runtime crash because of that error in the code is a failed dereference operation.

  8. Pointers in C Explained

    4. Strings. A string is a one-dimensional array of characters terminated by a null(\0).When we write char name[] = "Srijan";, each character occupies one byte of memory with the last one always being \0.. Similar to the arrays we have seen, name and &name[0] points to the 0th character in the string, while &name points to the whole string. Also, name[i] can be written as *(name + i).

  9. Pointers to Pointers

    86 Share 2.1K views 1 year ago Complete C Programming Course for Beginners to Advanced | WsCube Tech 2.0 In this video, learn Pointers to Pointers - How do you Set a Pointer to Another...

  10. c

    If you set one pointer equal to another, you end up pointing to the same block of memory. If you actually assigned two different blocks, you should never want to then set one pointer to the other - you will be unable to free the memory. Most likely you intend to do a memcpy which allows you to copy the contents of one memory block to another:

  11. Pointers

    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. An interesting property of pointers is that they can be used to access the variable they point to directly. This is done by preceding the pointer name with the dereference operator ( * ).

  12. Pointer to Pointer in C Language with Examples

    Understanding Pointer to Pointer in C. Consider a regular pointer: int x = 10; int *p = &x; // 'p' is a pointer to 'x'. Here, p is a pointer that holds the address of x. Now, let's introduce a pointer to a pointer: int **pp = &p; // pp is a pointer to p, which is a pointer to x. Here, pp is a pointer to a pointer.

  13. An Essential Guide to Pointers in C Programming

    Declare a pointer to an int and assign the memory location of the numbers array to it: int *ptr = numbers; You do not need to use the "&" operator here because numbers is already, implicitly, a pointer type. The ptr variable now points to the first element in the array: printf ( "%d\n", *ptr); // 10.

  14. How to Use Pointers in C Programming

    To declare a pointer variable in C, we use the asterisk * symbol before the variable name. There are two ways to declare pointer variables in C: int *p; int* p; Both of these declarations are equivalent and they declare a pointer variable named "p" that can hold the memory address of an integer.

  15. Pointer Arithmetics in C with Examples

    Pointer Arithmetic is the set of valid arithmetic operations that can be performed on pointers. The pointer variables store the memory address of another variable. It doesn't store any value. Hence, there are only a few operations that are allowed to perform on Pointers in C language. The C pointer arithmetic operations are slightly different ...

  16. How C-Pointers Works: A Step-by-Step Beginner's Tutorial

    This step is essential because it sets up the pointer to hold a specific memory address, enabling us to interact with the data stored at that location. Declaring Pointers: To declare a pointer, you specify the data type it points to, followed by an asterisk (*), and then the pointer's name.

  17. Directly assigning values to C Pointers

    51 I've just started learning C and I've been running some simple programs using MinGW for Windows to understand how pointers work. I tried the following: #include <stdio.h> int main () { int *ptr; *ptr = 20; printf ("%d", *ptr); return 0; }

  18. Pointers in C

    Consider the statement int num = 10; For the above statement, the C compiler allocates memory capable to store an integer. Let say memory is allocated at address 0x1200. After memory allocation, the C compiler defines a label (variable name) to access the memory location. The label is mapped to the allocated memory.

  19. how to use a pointer to point to another pointer in c++

    1 suppose that I have a pointer called P with float type which is points to some values. I want to creat another pointer called Ptr to go through where the P is pointing to and return the last element. How Can I do that? this is what I tried until now... float *p; float *ptr; for (int i=0; i< sizeof p; i++) { ptr++; return &ptr; }

  20. C++ Pointers

    Assigning the address of a variable to a pointer using the unary operator (&) which returns the address of that variable. Accessing the value stored in the address using unary operator (*) which returns the value of the variable located at the address specified by its operand.

  21. What happens if Fulton County DA Fani Willis is disqualified from the

    Fulton County Superior Court Judge Scott McAfee held an evidentiary hearing on Thursday and Friday over misconduct allegations that have been aimed at Willis and the special prosecutor she ...

  22. C++ Assign Pointer to Pointer

    3 Answers Sorted by: 10 In both examples, you are dereferencing an uninitialized pointer, which is undefined behaviour. For the pointer assignment question, you can directly assign: int *ptr2 = ptr2; in your second example, provided you make sure ptr1 points at a valid location. For example,

  23. 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.