• View source

In general, pointer is a type of a variable that stores a link to another object. In C and C++, the link is the address of that object in the program memory. Pointers allow to refer to the same object from multiple locations of the source code without copying the object. Also, the same pointer variable may refer to different objects during its lifetime.

A similar, more restricted type is a reference .

This section is incomplete
Reason: restructure the article
Creation Using pointers Using pointers to objects Special null pointer Pointers and const Pitfalls Accessing uninitialized pointers Different lifetime of memory and pointer

A pointer is declared just like a variable but with * after the type:

This is a pointer, which can point to an integer. The pointer is not yet initialized, therefore it points to an undefined location and any access to it is undefined behaviour.

What the statement did behind the scenes is to reserve a memory area large enough to hold a memory address on the given system.

Notice that so far we didn't reserve any memory to hold the integer object that the pointer will point.

Using pointers

Assignment and access of pointers:

The code above takes the address of a ( & operator) and assigns it to the pointer px . Afterwards we retrieve the value, by so called dereferencing of the pointer, using the * operator and assign it to b .

In the example you see that px points to the memory of variable a and therefore will see any changes made to a . b however has a copy of the value of a and therefore doesn't change.

Pointer can be assigned to other pointers of the same type just like variables. In this case the address inside the pointer is copied and both pointer point to the same location after the assignment.

Using pointers to objects

If pointers refer to objects which are not plain old data types, there is an easier syntax to access the members of the object.

Accessing members of objects could be done by dereferencing the pointer and accessing the function or variable of the object using the . operator. Or simply do both in a nicer syntax using the -> operator.

Special null pointer

Sometimes it is desirable to mark a pointer as invalid. This can be achieved by the assignment of nullptr to the pointer. This pointer is called a null pointer and dereferencing it results in undefined behavior.

A special feature of a null pointer is that it is the only possible pointer value that evaluates to false when converted to bool .

Before the C++11 standard, the standard way to refer to null pointers was by using NULL macro constant. Unfortunately, this method has a serious issue of being type-unsafe as NULL evaluates to an integer, not a pointer.

Consider the following example:

It is obvious that the intent of the programmer was to call the first overload of the foo function in both cases. However, as NULL is an integral constant, the second overload is called, which is unexpected behavior and may lead to a bug.

Pointers and const

Since pointers access memory of a certain type, like variables, and are variables themselves they have two const parameters.

If the pointer is const, we can't assign a different address to it. The pointer will always point to the same part of memory.

If the value is constant, we are able to assign a different address to the pointer, but we can't change the value it points to.

Accessing uninitialized pointers

Pointers should always be initialized with a valid address or nullptr . But this doesn't prevent access to null pointers causing an exception or undesired behaviour.

Therefore pointers should be compared against nullptr before access, unless it is guaranteed that the pointer is valid.

Different lifetime of memory and pointer

SubFunc creates a variable and returns the pointer to the variable. When SubFunc returns, the variable x goes out of scope and its memory is freed. The pointer px will still point to the old address of x which might already be assigned to a different process. Accessing the address is undefined behaviour.

Memory for an integer is reserved using new. First px points to this memory, but later on it points to the memory of a . The reserved memory is still reserved, but the address is lost, because no pointer points to it any more.

  • Todo with reason
  • Community portal
  • Current events
  • Recent changes
  • Random page
  • What links here
  • Related changes
  • Upload file
  • Special pages
  • Printable version
  • Permanent link
  • Page information
  • This page was last modified on 19 December 2013, at 01:11.
  • This page has been accessed 46,129 times.
  • Privacy policy
  • About cppreference.com
  • Disclaimers

Powered by MediaWiki

  • Sign In / Suggest an Article

Current ISO C++ status

Upcoming ISO C++ meetings

Upcoming C++ conferences

Compiler conformance status

ISO C++ committee meeting

June 24-29, St. Louis, MO, USA

July 2-5, Folkestone, Kent, UK

pointers to members

Pointers to member functions, is the type of “pointer-to-member-function” different from “pointer-to-function”.

Consider the following function:

The type of this function is different depending on whether it is an ordinary function or a non- static member function of some class:

  • Its type is “ int (*)(char,float) ” if an ordinary function
  • Its type is “ int (Fred::*)(char,float) ” if a non- static member function of class Fred

Note: if it’s a static member function of class Fred , its type is the same as if it were an ordinary function: “ int (*)(char,float) ”.

How do I pass a pointer-to-member-function to a signal handler, X event callback, system call that starts a thread/task, etc?


Because a member function is meaningless without an object to invoke it on, you can’t do this directly (if The X Window System was rewritten in C++, it would probably pass references to objects around, not just pointers to functions; naturally the objects would embody the required function and probably a whole lot more).

As a patch for existing software, use a top-level (non-member) function as a wrapper which takes an object obtained through some other technique. Depending on the routine you’re calling, this “other technique” might be trivial or might require a little work on your part. The system call that starts a thread, for example, might require you to pass a function pointer along with a void* , so you can pass the object pointer in the void* . Many real-time operating systems do something similar for the function that starts a new task. Worst case you could store the object pointer in a global variable; this might be required for Unix signal handlers (but globals are, in general, undesired). In any case, the top-level function would call the desired member function on the object.

Here’s an example of the worst case (using a global). Suppose you want to call Fred::memberFn() on interrupt:

Note: static member functions do not require an actual object to be invoked, so pointers-to- static -member-functions are usually type-compatible with regular pointers-to-functions. However, although it probably works on most compilers, it actually would have to be an extern "C" non-member function to be correct, since “C linkage” doesn’t only cover things like name mangling, but also calling conventions, which might be different between C and C++.

Why do I keep getting compile errors (type mismatch) when I try to use a member function as an interrupt service routine?

This is a special case of the previous two questions, therefore read the previous two answers first.

Non- static member functions have a hidden parameter that corresponds to the this pointer. The this pointer points to the instance data for the object. The interrupt hardware/firmware in the system is not capable of providing the this pointer argument. You must use “normal” functions (non class members) or static member functions as interrupt service routines.

One possible solution is to use a static member as the interrupt service routine and have that function look somewhere to find the instance/member pair that should be called on interrupt. Thus the effect is that a member function is invoked on an interrupt, but for technical reasons you need to call an intermediate function first.

Why am I having trouble taking the address of a C++ function?

Short answer: if you’re trying to store it into (or pass it as) a pointer-to-function, then that’s the problem — this is a corollary to the previous FAQ.

Long answer: In C++, member functions have an implicit parameter which points to the object (the this pointer inside the member function). Normal C functions can be thought of as having a different calling convention from member functions, so the types of their pointers (pointer-to-member-function vs pointer-to-function) are different and incompatible. C++ introduces a new type of pointer, called a pointer-to-member, which can be invoked only by providing an object.

NOTE: do not attempt to “cast” a pointer-to-member-function into a pointer-to-function; the result is undefined and probably disastrous. E.g., a pointer-to-member-function is not required to contain the machine address of the appropriate function. As was said in the last example, if you have a pointer to a regular C function, use either a top-level (non-member) function, or a static (class) member function.

How can I avoid syntax errors when creating pointers to members?

Use a typedef .

Yea, right, I know: you are different. You are smart . You can do this stuff without a typedef . Sigh. I have received many emails from people who, like you, refused to take the simple advice of this FAQ. They wasted hours and hours of their time, when 10 seconds worth of typedef s would have simplified their lives. Plus, face it, you are not writing code that only you can read; you are hopefully writing your code that others will also be able to read — when they’re tired — when they have their own deadlines and their own challenges. So why intentionally make life harder on yourself and on others? Be smart: use a typedef .

Here’s a sample class:

The typedef is trivial:

That’s it! FredMemFn is the type name, and a pointer of that type points to any member of Fred that takes (char,float) , such as Fred ’s f , g , h and i .

It’s then trivial to declare a member-function pointer:

And it’s also trivial to declare functions that receive member-function pointers:

And it’s also trivial to declare functions that return member-function pointers:

So please, use a typedef . Either that or do not send me email about the problems you have with your member-function pointers!

How can I avoid syntax errors when calling a member function using a pointer-to-member-function?

If you have access to a compiler and standard library that implements the appropriate parts of the upcoming C++17 standard, use std::invoke . Otherwise, use a #define macro.

Pretty please.

I get way too many emails from confused people who refused to take this advice. It’s so simple. I know, you don’t need std::invoke or a macro, and the expert you talked to can do it without either of them, but please don’t let your ego get in the way of what’s important: money. Other programmers will need to read / maintain your code. Yes, I know: you are smarter than everyone else; fine. And you are awesome; fine. But don’t add unnecessary complexity to your code.

Using std::invoke is trivial. Note: FredMemFn is a typedef for a pointer-to-member type :

If you can’t use std::invoke , reduce maintenance cost by, paradoxically , using a #define macro in this particular case.

( Normally I dislike #define macros , but you should use them with pointers to members because they improve the readability and writability of that sort of code.)

The macro is trivial:

Using the macro is also trivial. Note: FredMemFn is a typedef for a pointer-to-member type :

The reason std::invoke or this macro is a good idea is because member function invocations are often a lot more complex than the simple example just given. The difference in readability and writability is significant. comp.lang.c++ has had to endure hundreds and hundreds of postings from confused programmers who couldn’t quite get the syntax right. Almost all these errors would have vanished had they used std::invoke or the above macro.

Note: #define macros are evil in 4 different ways: evil#1 , evil#2 , evil#3 , and evil#4 . But they’re still useful sometimes . But you should still feel a vague sense of shame after using them.

How do I create and use an array of pointer-to-member-function?

Use both the typedef and std::invoke or the #define macro described earlier , and you’re 90% done.

Step 1: create a typedef :

Step 2: create a #define macro if you don’t have std::invoke :

Now your array of pointers-to-member-functions is straightforward:

And your usage of one of the member function pointers is also straightforward:

or if you don’t have std::invoke ,

Note: #define macros are evil in 4 different ways: evil#1 , evil#2 , evil#3 , and evil#4 . But they’re still useful sometimes. Feel ashamed, feel guilty, but when an evil construct like a macro improves your software, use it .

How do I declare a pointer-to-member-function that points to a const member function?

Short answer: add a const to the right of the ) when you use a typedef to declare the member-function-pointer type .

For example, suppose you want a pointer-to-member-function that points at Fred::f , Fred::g or Fred::h :

Then when you use a typedef to declare the member-function-pointer type , it should look like this:

That’s it!

Then you can declare/pass/return member-function pointers just like normal:

What is the difference between the .* and ->* operators?

You won’t need to understand this if you use std::invoke or a macro for member-function-pointer calls . Oh yea, please use std::invoke or a macro in this case . And did I mention that you should use std::invoke or a macro in this case ??!?

But if you really want to avoid std::invoke or the macro, sigh, groan, okay, here it is: use .* when the left-hand argument is a reference to an object, and ->* when it is a pointer to an object.

For example:

BUT please consider using a std::invoke or macro instead :

As discussed earlier , real-world invocations are often much more complicated than the simple ones here, so using a std::invoke or macro will typically improve your code’s writability and readability.

Can I convert a pointer-to-member-function to a void* ?

Technical details: pointers to member functions and pointers to data are not necessarily represented in the same way. A pointer to a member function might be a data structure rather than a single pointer. Think about it: if it’s pointing at a virtual function, it might not actually be pointing at a statically resolvable pile of code, so it might not even be a normal address — it might be a different data structure of some sort.

Please do not email me if the above seems to work on your particular version of your particular compiler on your particular operating system. I don’t care. It’s illegal, period.

Can I convert a pointer-to-function to a void* ?

Technical details: void* pointers are pointers to data, and function pointers point to functions. The language does not require functions and data to be in the same address space, so, by way of example and not limitation , on architectures that have them in different address spaces, the two different pointer types will not be comparable.

I need something like function-pointers, but with more flexibility and/or thread-safety; is there another way?

Use a functionoid.

What the heck is a functionoid, and why would I use one?

Functionoids are functions on steroids. Functionoids are strictly more powerful than functions, and that extra power solves some (not all) of the challenges typically faced when you use function-pointers.

Let’s work an example showing a traditional use of function-pointers, then we’ll translate that example into functionoids. The traditional function-pointer idea is to have a bunch of compatible functions:

Then you access those by function-pointers:

Sometimes people create an array of these function-pointers:

In which case they call the function by accessing the array:

With functionoids, you first create a base class with a pure-virtual method:

Then instead of three functions, you create three derived classes:

Then instead of passing a function-pointer, you pass a Funct* . I’ll create a typedef called FunctPtr merely to make the rest of the code similar to the old-fashioned approach:

You can create an array of them in almost the same way:

This gives us the first hint about where functionoids are strictly more powerful than function-pointers: the fact that the functionoid approach has arguments you can pass to the ctors (shown above as …ctor-args… ) whereas the function-pointers version does not. Think of a functionoid object as a freeze-dried function-call (emphasis on the word call ). Unlike a pointer to a function, a functionoid is (conceptually) a pointer to a partially called function. Imagine for the moment a technology that lets you pass some-but-not-all arguments to a function, then lets you freeze-dry that (partially completed) call. Pretend that technology gives you back some sort of magic pointer to that freeze-dried partially-completed function-call. Then later you pass the remaining args using that pointer, and the system magically takes your original args (that were freeze-dried), combines them with any local variables that the function calculated prior to being freeze-dried, combines all that with the newly passed args, and continues the function’s execution where it left off when it was freeze-dried. That might sound like science fiction, but it’s conceptually what functionoids let you do. Plus they let you repeatedly “complete” that freeze-dried function-call with various different “remaining parameters,” as often as you like. Plus they allow (not require) you to change the freeze-dried state when it gets called, meaning functionoids can remember information from one call to the next.

Let’s get our feet back on the ground and we’ll work a couple of examples to explain what all that mumbo jumbo really means.

Suppose the original functions (in the old-fashioned function-pointer style) took slightly different parameters.

When the parameters are different, the old-fashioned function-pointers approach is difficult to use, since the caller doesn’t know which parameters to pass (the caller merely has a pointer to the function, not the function’s name or, when the parameters are different, the number and types of its parameters) (do not write me an email about this; yes you can do it, but you have to stand on your head and do messy things; but do not write me about it — use functionoids instead).

With functionoids, the situation is, at least sometimes, much better. Since a functionoid can be thought of as a freeze-dried function call , just take the un-common args, such as the ones I’ve called y and/or z , and make them args to the corresponding ctors. You may also pass the common args (in this case the int called x ) to the ctor, but you don’t have to — you have the option of passing it/them to the pure virtual doit() method instead. I’ll assume you want to pass x into doit() and y and/or z into the ctors:

Now you see that the ctor’s parameters get freeze-dried into the functionoid when you create the array of functionoids:

So when the user invokes the doit() on one of these functionoids, he supplies the “remaining” args, and the call conceptually combines the original args passed to the ctor with those passed into the doit() method:

As I’ve already hinted, one of the benefits of functionoids is that you can have several instances of, say, Funct1 in your array, and those instances can have different parameters freeze-dried into them. For example, array[0] and array[1] are both of type Funct1 , but the behavior of array[0]->doit(12) will be different from the behavior of array[1]->doit(12) since the behavior will depend on both the 12 that was passed to doit() and the args passed to the ctors.

Another benefit of functionoids is apparent if we change the example from an array of functionoids to a local functionoid. To set the stage, let’s go back to the old-fashioned function-pointer approach, and imagine that you’re trying to pass a comparison-function to a sort() or binarySearch() routine. The sort() or binarySearch() routine is called childRoutine() and the comparison function-pointer type is called FunctPtr :

Then different callers would pass different function-pointers depending on what they thought was best:

We can easily translate this example into one using functionoids:

Given this example as a backdrop, we can see two benefits of functionoids over function-pointers. The “ctor args” benefit described above, plus the fact that functionoids can maintain state between calls in a thread-safe manner . With plain function-pointers, people normally maintain state between calls via static data. However static data is not intrinsically thread-safe — static data is shared between all threads. The functionoid approach provides you with something that is intrinsically thread-safe since the code ends up with thread-local data. The implementation is trivial: change the old-fashioned static datum to an instance data member inside the functionoid’s this object, and poof, the data is not only thread-local, but it is even safe with recursive calls: each call to yourCaller() will have its own distinct Funct3 object with its own distinct instance data.

Note that we’ve gained something without losing anything. If you want thread-global data, functionoids can give you that too: just change it from an instance data member inside the functionoid’s this object to a static data member within the functionoid’s class, or even to a local-scope static data. You’d be no better off than with function-pointers, but you wouldn’t be worse off either.

The functionoid approach gives you a third option which is not available with the old-fashioned approach: the functionoid lets callers decide whether they want thread-local or thread-global data. They’d be responsible to use locks in cases where they wanted thread-global data, but at least they’d have the choice. It’s easy:

Functionoids don’t solve every problem encountered when making flexible software, but they are strictly more powerful than function-pointers and they are worth at least evaluating. In fact you can easily prove that functionoids don’t lose any power over function-pointers, since you can imagine that the old-fashioned approach of function-pointers is equivalent to having a global(!) functionoid object. Since you can always make a global functionoid object, you haven’t lost any ground. QED.

Can you make functionoids faster than normal function calls?

If you have a small functionoid, and in the real world that’s rather common, the cost of the function-call can be high compared to the cost of the work done by the functionoid. In the previous FAQ , functionoids were implemented using virtual functions and will typically cost you a function-call. An alternate approach uses templates .

The following example is similar in spirit to the one in the previous FAQ . I have renamed doit() to operator()() to improve the caller code’s readability and to allow someone to pass a regular function-pointer:

The difference between this approach and the one in the previous FAQ is that the fuctionoid gets “bound” to the caller at compile-time rather than at run-time. Think of it as passing in a parameter: if you know at compile-time the kind of functionoid you ultimately want to pass in, then you can use the above technique, and you can, at least in typical cases , get a speed benefit from having the compiler inline-expand the functionoid code within the caller. Here is an example:

When the compiler compiles the above, it might inline-expand the call which might improve performance.

Here is one way to call the above:

Aside: as was hinted at in the first paragraph above, you may also pass in the names of normal functions (though you might incur the cost of the function call when the caller uses these):

What’s the difference between a functionoid and a functor?

A functionoid is an object that has one major method. It’s basically the OO extension of a C-like function such as printf(). One would use a functionoid whenever the function has more than one entry point (i.e., more than one “method”) and/or needs to maintain state between calls in a thread-safe manner (the C-style approach to maintaining state between calls is to add a local “static” variable to the function, but that is horribly unsafe in a multi-threaded environment).

A functor is a special case of a functionoid: it is a functionoid whose method is the “function-call operator,” operator()(). Since it overloads the function-call operator, code can call its major method using the same syntax they would for a function call. E.g., if “foo” is a functor, to call the “operator()()” method on the “foo” object one would say “foo()”. The benefit of this is in templates, since then the template can have a template parameter that will be used as a function, and this parameter can be either the name of a function or a functor-object. There is a performance advantage of it being a functor object since the “operator()()” method can be inlined (whereas if you pass the address of a function it must, necessarily, be non-inlined).

This is very useful for things like the “comparison” function on sorted containers. In C, the comparison function is always passed by pointer (e.g., see the signature to “qsort()”), but in C++ the parameter can come in either as a pointer to function OR as the name of a functor-object, and the result is that sorted containers in C++ can be, in some cases, a lot faster (and never slower) than the equivalent in C.

Since Java has nothing similar to templates, it must use dynamic binding for all this stuff, and dynamic binding of necessity means a function call. Normally not a big deal, but in C++ we want to enable extremely high performance code. That is, C++ has a “pay for it only if you use it” philosophy, which means the language must never arbitrarily impose any overhead over what the physical machine is capable of performing (of course a programmer may, optionally, use techniques such as dynamic binding that will, in general, impose some overhead in exchange for flexibility or some other “ility”, but it’s up to the designer and programmer to decide whether they want the benefits (and costs) of such constructs).

Please Login to submit a recommendation.

If you don’t have an account, you can register for free.

Pointer To Object In C++

C++ Course: Learn the Essentials

A pointer is a variable that stores the memory address of another variable (or object) as its value. A pointer aims to point to a data type which may be int, character, double, etc.

Pointers to objects aim to make a pointer that can access the object, not the variables. Pointer to object in C++ refers to accessing an object.

There are two approaches by which you can access an object. One is directly and the other is by using a pointer to an object in C++.

  • A pointer to an object in C++ is used to store the address of an object. For creating a pointer to an object in C++, we use the following syntax:

For storing the address of an object into a pointer in c++, we use the following syntax:

The above syntax can be used to store the address in the pointer to the object. After storing the address in the pointer to the object, the member function can be called using the pointer to the object with the help of an arrow operator.

Now, let us see some examples and understand the pointer to the object in c++ in a better way.

Example 1. In the below example, a simple class named My_Class is created. An object of the class is defined as named object . Here a pointer is also defined named p . In the program given below program, it is shown how can we access the object directly and how can we use the pointer to access the object directly.

Explanation : The address of the object named object is accessed by using the address of (&) operator. Whenever there is any increment or decrement in the pointer, it changes in such a way that the pointer will aim at the next element of that particular base class. Also, the same thing happens whenever there is any change in a pointer to an object. The change here refers to any increment or decrement in the pointer.

For showing this, there are some modifications done in the above program so that the object will be a two-dimensional array of type My_Class . Now, the pointer p will be once incremented and then decremented for accessing the two elements in the array.

Example 2. In the below example, we used a pointer to an object and an arrow operator.

Explanation : A class name Complex is created in the above program. It contains two primitive data members. One is real and the other is imaginary . There are also two member functions inside the class. One is get_data and the other one is set_data . The work of function set_data is that it will take two parameters and assign the value of these parameters to the data members that are- real and imaginary . The work of function get_data is that it will print the values of data members that are real and imaginary .

The main program consists of an object that is created dynamically with the help of the new keyword. The address of this object is assigned to the pointer named ptr . Then the get_data is called. This calling of a member function is done by the pointer using the arrow -> operator. The set_data is then called by using a pointer with the help of the arrow -> operator.

Pointer ptr is used to call the member function get_data and set_data and it will print the values 1, 54 and 1, 4 respectively. Here we used an arrow operator instead of a dot ( . ) operator but it gives the same expected output.

let us have a brief grasp of the basic concepts of pointers that will help to understand pointer to object in c++ in a better way and that will be a prerequisite for a pointer to object in c++.

In simple terms, a pointer is a variable that stores the memory address of another variable (or object) as its value. A pointer aims to point to a data type which may be int, character, double, etc. But a pointer always points to a data type of the same type. Pointers are created by using the * operator.

  • Types of pointers in c++ There are majorly four types of pointers in C++:
  • Null Pointer : As the name suggests, a null pointer is a type of pointer which represents nothing.
  • Void Pointer : A void Pointer is a type of pointer which does not point to any data type. We can say that it is a general-purpose pointer.
  • Wild Pointer : Wild pointers are similar to normal pointers but one thing that makes them different is they are only declared but not initialized. Since they are only initialized they point to unallocated memory.
  • Dangling Pointer : A dangling pointer is a type of pointer that comes when we deallocate the object but forgets to modify the value of the pointer.

Objects in c++ are defined as the instance of a class. It is also referred to as a piece of code that represents the member of its class of variables of its class. An object can access all the members of its class. So, we can also say a class is a collection of many objects inside it. An object can be created many times but a class can be defined once only.

  • Syntax for objects in c++ : The syntax of defining an object in c++ is done as given below.

When we create an object, all the members of the class are defined inside that particular class. These objects can access the data members with the help of a dot(.) operator.

What are the Advantages of using Pointer to Objects in C++?

  • Pointers can be used to store the memory address of a variable. The syntax for this is as follows.

Example In the example given below, ptr stores the address of an integer variable. Using this pointer we can access the memory address of that particular variable int .

  • Using a pointer to an object in c++, we can save memory space and we can directly manipulate the memory.
  • Execution becomes faster when we use pointers because a pointer manipulates the memory address of data rather than accessing the data.
  • Pointer to object in c++ is used with data structures like two-dimensional arrays and multi-dimensional arrays.
  • Pointers to objects can be used for File Handling .
  • When we declare a pointer to the base class, then an object of the derived class can be accessed by the base class.
  • Pointer to object in c++ can be used to dynamically allocate the memory.

Learn More About Pointers in C++

To learn more about pointers in C++ Read our Article .

  • Pointer to object in c++ is defined as the pointer that is used for accessing objects.
  • A pointer is a variable that stores the memory address of another variable.
  • The types of the pointer are Null pointer, Void pointer, Wild pointer, and Dangling pointer.
  • An object is defined as the instance of a class.
  • These objects can access the data members with the help of a dot(.) operator.
  • Pointer to object in c++ helps to execute a program faster.
  • Pointer to object can be used for File Handling.

CProgramming Tutorial

  • C Programming Tutorial
  • Basics of C
  • 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 - Type Casting
  • C - Booleans
  • Constants and Literals in C
  • C - Constants
  • C - Literals
  • C - Escape sequences
  • C - Format Specifiers
  • Operators in C
  • C - Operators
  • C - Arithmetic Operators
  • C - Relational Operators
  • C - Logical Operators
  • C - Bitwise Operators
  • C - Assignment Operators
  • C - Unary Operators
  • C - Increment and Decrement Operators
  • C - Ternary Operator
  • C - sizeof Operator
  • C - Operator Precedence
  • C - Misc Operators
  • Decision Making in C
  • C - Decision Making
  • C - if statement
  • C - if...else statement
  • C - nested if statements
  • C - switch statement
  • C - nested switch statements
  • C - While loop
  • C - For loop
  • C - Do...while loop
  • C - Nested loop
  • C - Infinite loop
  • C - Break Statement
  • C - Continue Statement
  • C - goto Statement
  • Functions in C
  • C - Functions
  • C - Main Function
  • C - Function call by Value
  • C - Function call by reference
  • C - Nested Functions
  • C - Variadic Functions
  • C - User-Defined Functions
  • C - Callback Function
  • C - Return Statement
  • C - Recursion
  • Scope Rules in C
  • C - Scope Rules
  • C - Static Variables
  • C - Global Variables
  • Arrays in C
  • C - Properties of Array
  • C - Multi-Dimensional Arrays
  • C - Passing Arrays to Function
  • C - Return Array from Function
  • C - Variable Length Arrays
  • Pointers in C
  • C - Pointers
  • C - Pointers and Arrays
  • C - Applications of Pointers
  • C - Pointer Arithmetics
  • C - Array of Pointers
  • C - Pointer to Pointer
  • C - Passing Pointers to Functions
  • C - Return Pointer from Functions
  • C - Function Pointers
  • C - Pointer to an Array
  • C - Pointers to Structures
  • C - Chain of Pointers
  • C - Pointer vs Array
  • C - Character Pointers and Functions
  • C - NULL Pointer
  • C - void Pointer
  • C - Dangling Pointers
  • C - Dereference Pointer
  • C - Near, Far and Huge Pointers
  • C - Initialization of Pointer Arrays
  • C - Pointers vs. Multi-dimensional Arrays
  • Strings in C
  • C - Strings
  • C - Array of Strings
  • C - Special Characters
  • C Structures and Unions
  • C - Structures
  • C - Structures and Functions
  • C - Arrays of Structures
  • C - Self-Referential Structures
  • C - Lookup Tables
  • C - Dot (.) Operator
  • C - Enumeration (or enum)
  • C - Structure Padding and Packing
  • C - Nested Structures
  • C - Anonymous Structure and Union
  • C - Bit Fields
  • C - Typedef
  • File Handling in C
  • C - Input & Output
  • C - File I/O (File Handling)
  • C Preprocessors
  • C - Preprocessors
  • C - Pragmas
  • C - Preprocessor Operators
  • C - Header Files
  • Memory Management in C
  • C - Memory Management
  • C - Memory Address
  • C - Storage Classes
  • Miscellaneous Topics
  • C - Error Handling
  • C - Variable Arguments
  • C - Command Execution
  • C - Math Functions
  • C - Static Keyword
  • C - Random Number Generation
  • C - Command Line Arguments
  • C Programming Resources
  • C - Questions & Answers
  • C - Quick Guide
  • C - Cheat Sheet
  • 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

Pointer to Pointer (Double Pointer) in C

What is a double pointer in c.

A pointer to pointer which is also known as a double pointer in C is used to store the address of another pointer.

A variable in C that stores the address of another variable is known as a pointer . A pointer variable can store the address of any type including the primary data types, arrays, struct types, etc. Likewise, a pointer can store the address of another pointer too, in which case it is called "pointer to pointer" (also called "double 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

Declaration of Pointer to a Pointer

The declaration of a pointer to pointer ( double pointer ) is similar to the declaration of a pointer, the only difference is that you need to use an additional asterisk ( * ) before the pointer variable 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.

Example of Pointer to Pointer (Double Pointer)

The following example demonstrates the declaration, initialization, and using pointer to pointer (double pointer) in C:

How Does a Normal Pointer Work in C?

Assume that an integer variable "a" is located at an arbitrary address 1000. Its pointer variable is "b" and the compiler allocates it the address 2000. The following image presents a visual depiction −

Normal Pointer

Let us declare a pointer to int type and store the address of an int variable in it.

The dereference operator fetches the value via the pointer.

Here is the complete program that shows how a normal pointer works −

It will print the value of int variable, its address, and the value obtained by the dereference pointer −

How Does a Double Pointer Work?

Let us now declare a pointer that can store the address of "b", which itself is a pointer to int type written as "int *".

Let's assume that the compiler also allocates it the address 3000.

Double Pointer

Hence, "c" is a pointer to a pointer to int, and should be declared as "int **".

You get the value of "b" (which is the address of "a"), the value of "c" (which is the address of "b:), and the dereferenced value from "c" (which is the address of "a") −

Here, "c" is a double pointer. The first asterisk in its declaration points to "b" and the second asterisk in turn points to "a". So, we can use the double reference pointer to obtain the value of "a" from "c".

This should display the value of 'a' as 10.

Here is the complete program that shows how a double pointer works −

Run the code and check its output −

A Double Pointer Behaves Just Like a Normal Pointer

A "pointer to pointer" or a "double pointer" in C behaves just like a normal pointer. So, the size of a double pointer variable is always equal to a normal pointer.

We can check it by applying the sizeof operator to the pointers "b" and "c" in the above program −

This shows the equal size of both the pointers −

Note: The size and address of different pointer variables shown in the above examples may vary, as it depends on factors such as CPU architecture and the operating system. However, they will show consistent results.

Multilevel Pointers in C (Is a Triple Pointer Possible?)

Theoretically, there is no limit to how many asterisks can appear in a pointer declaration.

If you do need to have a pointer to "c" (in the above example), it will be a "pointer to a pointer to a pointer" and may be declared as −

Mostly, double pointers are used to refer to a two−dimensional array or an array of strings.

12.9 — Pointers and const

Pointer and const recap

C++ Overview

  • Introduction to C++
  • OOPS concepts basic
  • Basic Syntax and Structure
  • Data types and Modifiers
  • Variables in C++
  • Operators in C++
  • sizeof and typedef in C++
  • Decision Making
  • Storage Classes
  • Classes and Objects
  • Access Controls in classes
  • Defining class and object
  • Accessing Data Members
  • Member Functions in class
  • Types of Member Functions
  • Inline Functions
  • Function Overloading
  • Constructor and Destructor
  • Static Keyword
  • Const Keyword
  • Copy Constructor
  • Pointer to Members


  • Introduction to Inheritance
  • Types of Inheritance
  • Order of Constructor Call


  • Function Overriding
  • Virtual Functions
  • Abstract class and Pure Virtual Functions
  • Virtual Destructors
  • Operator Overloading
  • Operator Overloading Examples
  • File Streams
  • Exception Handling
  • Memory Management
  • Multithreading
  • Initializer List
  • Defining Namespace

C++ Programs

  • 100+ C++ Programs with explanation and output.

Pointers to Class Members in C++

Just like pointers to normal variables and functions, we can have pointers to class member functions and member variables.

Let's see how this works.

Defining a Pointer of Class type

We can define pointer of class type, which can be used to point to class objects.

Here you can see that we have declared a pointer of class type which points to class's object. We can access data members and member functions using pointer name with arrow -> symbol.

Pointer to Data Members of Class

We can use pointer to point to class's data members (Member variables).

Syntax for Declaration :

Syntax for Assignment:

Both declaration and assignment can be done in a single statement too.

Using Pointers with Objects

For accessing normal data members we use the dot . operator with object and -> qith pointer to object. But when we have a pointer to data member, we have to dereference that pointer to get what its pointing to, hence it becomes,

and with pointer to object, it can be accessed by writing,

Lets take an example, to understand the complete concept.

a is 10 a is 20

The syntax is very tough, hence they are only used under special circumstances.

Pointer to Member Functions of Class

Pointers can be used to point to class's Member functions.

Below is an example to show how we use ppointer to member functions.

Some Points to remember

  • You can change the value and behaviour of these pointers on runtime. That means, you can point it to other member function or member variable.
  • To have pointer to data member and member functions you need to make them public.
  • ← Prev
  • Next →

  STL Tutorial

  data structures & algo,   c++ mcq tests.

C++ Class Introduction

C++ class syntax, c++ class member data fields, c++ class member functions, c++ class access specifiers, c++ structure as class, c++ class this keyword, c++ pointers to objects, c++ arrays of objects, c++ initializing object arrays, c++ objects assigning, c++ class friend functions, c++ class inline functions, c++ class member access, c++ dynamic memory in param, c++ passing objects, c++ returning objects, c++ returning objects risk, c++ class constructors, c++ class constructor call, c++ class member initialization, c++ copy constructor, c++ copy assignment, c++ class move constructor, c++ class move assignment, c++ copy constructors in return, c++ copy construct in init, c++ copy constructors in param, c++ copy constructor usage, c++ passing objects destructing, c++ initialization alternative, c++ constructor overloading, c++ parameterized constructors, c++ class destructors, c++ static local variable, c++ static class member fields, c++ static class member functions, c++ unscoped enum type, c++ scoped enum type, c++ class exercise 1, c++ class exercise 2, c++ class exercise 3, c++ class exercise 4.

You can access an object either directly, or by using a pointer to the object.

To access an element of an object when using the actual object itself, use the dot operator.

To access a specific element of an object when using a pointer to the object, you must use the arrow operator.

To declare an object pointer, you use the same declaration syntax that you would use for any other pointer type.

The next program creates a simple class called My_Class , defines an object of that class, called ob , and defines a pointer to an object of type My_Class , called p.

It then illustrates how to access ob directly, and how to use a pointer to access it indirectly.

Notice that the address of ob is obtained by using the & (address of) operator in the same way that the address is obtained for any type of variable.

When a pointer is incremented or decremented, it is increased or decreased in such a way that it will always point to the next element of its base type.

The same thing occurs when a pointer to an object is incremented or decremented: the next object is pointed to.

To illustrate this, the preceding program has been modified here so that ob is a two-element array of type My_Class .

Notice how p is incremented and decremented to access the two elements in the array.

The output from this program is.

  • Windows Programming
  • UNIX/Linux Programming
  • General C++ Programming
  • Assigning class objects to pointers

  Assigning class objects to pointers

assign pointer to object c

assignPointers(Car*, Car**)â: PROG6/prog6.cpp:73: error: cannot convert âCarâ to âCar*â in assignment
std; readFile (ifstream&, Car[]); sortByModel(Car[]); searchByModel(Car[]); assignPointers(Car[], Car*[]); main () { Car* carPtr[10]; Car carArray[10]; ifstream fin; string ifName; cout << ; cin >> ifName; fin.open(ifName.c_str()); (fin.fail()) { cout << ; } readFile (fin, carArray); assignPointers(carArray, carPtr); } readFile (ifstream&inFile, Car carArr[]) { ( i=0; i < 10; i++) { string aMake, aModel; aYear; aValue; getline(inFile, aMake); getline(inFile, aModel); inFile >> aYear; inFile >> aValue; carArr[i].setMake(aMake); carArr[i].setModel(aModel); carArr[i].setYear(aYear); carArr[i].setValue(aValue); inFile.ignore(100, ); inFile.ignore(100, ); (inFile.eof()) { ; } } } assignPointers(Car carArr[], Car*carPoint[]) { ( j=0; j < 10; j++) { carPoint[j] = carArr[j]; } }
std; Car { : string make; string model; year; value; : Car (string, string, , ); Car (); setMake (string); setModel (string); setYear ( ); setValue ( ); string getMake(); string getModel(); getYear(); getValue(); print(ofstream&); print(); ofstream outFile; }; Car::Car(string make, string model, year, value) {} Car::Car() : make( ), model( ), year(2012), value(0.00) {} Car::setMake(string carMake ) { make = carMake; } Car::setModel(string carModel ) { model = carModel; } Car::setYear( carYear) { year = carYear; (year < 1769 || year > 2012) { year = 2012; } } Car::setValue( carValue) { value = carValue; (value < 0) { value = 0.00; } } string Car:: getMake() { make; } string Car::getModel() { model; } Car::getYear() { year; } Car::getValue() { value; } Car::print(ofstream&outFile) { outFile << setw(6) << left << year << setw(15) << left << make << setw(20) << left << model << setw(10) << setprecision(2) << fixed << right << value << endl; } Car::print() { cout << setw(6) << left << year << setw(15) << left << make << setw(20) << left << model << setw(10) << setprecision(2) << fixed << right << value << endl; }

MIT Technology Review

  • Newsletters

How to fix a Windows PC affected by the global outage

There is a known workaround for the blue screen CrowdStrike error that many Windows computers are currently experiencing. Here’s how to do it.

  • Rhiannon Williams archive page

BARCELONA, SPAIN - JULY 19: A passenger takes pictures of a screen displaying delayed flights at Barcelona Aiport on July 19, 2024 in Barcelona, Spain. Businesses, travel companies and Microsoft users across the globe were among those affected by a tech outage today. (Photo by David Ramos/Getty Images)

MIT Technology Review Explains: Let our writers untangle the complex, messy world of technology to help you understand what's coming next. You can read more here.

Windows PCs have crashed in a major IT outage around the world, bringing airlines, major banks, TV broadcasters, health-care providers, and other businesses to a standstill. Airlines including United, Delta, and American have been forced to ground and delay flights, stranding passengers in airports, while the UK broadcaster Sky News was temporarily pulled off air. Meanwhile, banking customers in Europe, Australia, and India have been unable to access their online accounts. Doctor’s offices and hospitals in the UK have lost access to patient records and appointment scheduling systems. 

The problem stems from a defect in a single content update for Windows machines from the cybersecurity provider CrowdStrike. George Kurtz, CrowdStrike’s CEO, says that the company is actively working with customers affected. “This is not a security incident or cyberattack,” he said in a statement on X. “The issue has been identified, isolated and a fix has been deployed. We refer customers to the support portal for the latest updates and will continue to provide complete and continuous updates on our website.” CrowdStrike pointed MIT Technology Review to its blog with additional updates for customers.

What caused the issue?

The issue originates from a faulty update from CrowdStrike, which has knocked affected servers and PCs offline and caused some Windows workstations to display the “blue screen of death” when users attempt to boot them. Mac and Linux hosts are not affected.

The update was intended for CrowdStrike’s Falcon software, which is “endpoint detection and response” software designed to protect companies’ computer systems from cyberattacks and malware. But instead of working as expected, the update caused computers running Windows software to crash and fail to reboot. Home PCs running Windows are less likely to have been affected, because CrowdStrike is predominantly used by large organizations. Microsoft did not immediately respond to a request for comment.

“The CrowdStrike software works at the low-level operating system layer. Issues at this level make the OS not bootable,” says Lukasz Olejnik, an independent cybersecurity researcher and consultant, and author of Philosophy of Cybersecurity .

Not all computers running Windows were affected in the same way, he says, pointing out that if a machine’s systems had been turned off at the time CrowdStrike pushed out the update (which has since been withdrawn), it wouldn’t have received it. For the machines running systems that received the mangled update and were rebooted, an automated update from CloudStrike’s server management infrastructure should suffice, he says.

“But in thousands or millions of cases, this may require manual human intervention,” he adds. “That means a really bad weekend ahead for plenty of IT staff.”

How to manually fix your affected computer

There is a known workaround for Windows computers that requires administrative access to its systems. If you’re affected and have that high level of access, CrowdStrike has recommended the following steps:

1. Boot Windows into safe mode or the Windows Recovery Environment.

2. Navigate to the C:\Windows\System32\drivers\CrowdStrike directory.

3. Locate the file matching “C-00000291*.sys” and delete it.

4. Boot the machine normally.

Sounds simple, right? But while the above fix is fairly easy to administer, it requires someone to enter it physically, meaning IT teams will need to track down remote machines that have been affected, says Andrew Dwyer of the Department of Information Security at Royal Holloway, University of London.

“We’ve been quite lucky that this is an outage and not an exploitation by a criminal gang or another state,” he says. “It also shows how easy it is to inflict quite significant global damage if you get into the right part of the IT supply chain.” While fixing the problem is going to cause headaches for IT teams for the next week or so, it’s highly unlikely to cause significant long-term damage to the affected systems—which would not have been the case if it had been ransomware rather than a bungled update, he says.

Keep Reading

Most popular, what is ai.

Everyone thinks they know but no one can agree. And that’s a problem.

  • Will Douglas Heaven archive page

What are AI agents? 

The next big thing is AI tools that can do more complex tasks. Here’s how they will work.

  • Melissa Heikkilä archive page

What’s next for bird flu vaccines

If we want our vaccine production process to be more robust and faster, we’ll have to stop relying on chicken eggs.

  • Cassandra Willyard archive page

How to use AI to plan your next vacation

AI tools can be useful for everything from booking flights to translating menus.

Stay connected

Get the latest updates from mit technology review.

Discover special offers, top stories, upcoming events, and more.

Thank you for submitting your email!

It looks like something went wrong.

We’re having trouble saving your preferences. Try refreshing this page and updating them one more time. If you continue to get this message, reach out to us at [email protected] with a list of newsletters you’d like to receive.

  • C++ Data Types

C++ Input/Output

C++ pointers, c++ interview questions.

  • C++ Programs
  • C++ Cheatsheet
  • C++ Projects

C++ Exception Handling

  • C++ Memory Management
  • 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 in C

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

Similar reads.

  • cpp-pointer

Improve your Coding Skills with Practice


What kind of Experience do you want to share?

Suspect came within inches of killing Trump, but left few clues as to why

  • Medium Text


Investigation begins after gunfire during a campaign rally by Trump in Butler, Pennsylvania

Sign up here.

Reporting by Nathan Layne and Gabriella Borter in Bethel Park, Jasper Ward and Kanishka Singh in Washington; Additional reporting by Aaron Josefczyk in Bethel Park, Brendan O'Brien in Chicago, Tyler Clifford in New York, and Daniel Trotta in Carlsbad, California; Editing by Paul Thomasch, Lisa Shumaker and Lincoln Feast.

Our Standards: The Thomson Reuters Trust Principles. , opens new tab

assign pointer to object c

Thomson Reuters

Gabriella Borter is a reporter on the U.S. National Affairs team, covering cultural and political issues as well as breaking news. She has won two Front Page Awards from the Newswomen’s Club of New York - in 2020 for her beat reporting on healthcare workers during the COVID-19 pandemic, and in 2019 for her spot story on the firing of the police officer who killed Eric Garner. The latter was also a Deadline Club Awards finalist. She holds a B.A. in English from Yale University and joined Reuters in 2017.

House Oversight Committee holds hearing on Capitol Hill, in Washington

Israeli settlers court Republican religious right after Hamas attacks

Ruth Lieberman, a Jewish settler in the Israeli occupied West Bank, is determined to thwart international pressure for a sovereign Palestinian state. And her friendships with prominent U.S. Republicans from the party's religious right are helping, she says.

Bottles of vodka are displayed for sale in a supermarket in Moscow

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

Assigning a value to a pointer

If I have the following for example:

For the statement: x = func(a); , do we say that we are returning an address to x ? Or, how exactly do we read it?

EDIT : Is it eligible to say that we are returning a pointer to x ? If so, can you explain how this is done exactly? I mean, how are we returning a pointer?

Lightness Races in Orbit's user avatar

7 Answers 7

x is a pointer to an int , so in other words it is the address of a memory location where an int is stored. So x = func(a) means that func returns the address of an int and stores it in the variable x .

Take care not to return the address of a local variable whose contents would be undefined after func returns.

Alexander Gessler's user avatar

RE: Your edit:

EDIT: Is it eligible to say that we are returning a pointer to x? If so, can you explain how is this done exactly? I mean, how are we returning a pointer?

Yes, it is certainly eligible. Try and think of and treat pointers as any other data type. Under the hood, they are just memory addresses. A pointer can be returned the same way any other data type can be returned.

Take this code for example:

Say that "y" is declared globally as: "int* y = ...". Now the memory address being pointed to by "x" is the same as the memory address being pointed to by "y".

Now let's say that "y" was -not- declared as a pointer, but instead as a normal int (e.g. "int y = 5"). The function could do this and still be valid:

AlexFZ's user avatar

*x is points to int typed variable in memory. So function func should return address to int.

For example the getGlobalCounter function:

But isn't always good idea to delete objects returned from functions. In that case it should result in runtime error, because of counter isn't dynamically allocated int as in top example.

kravemir's user avatar

If you are assigning a variable's value to the return-type of a function, then that return-type must match the variable's type. This goes the same for pointers.

So, if you have:

Then setting myPointer equal to func() will change the memory address which "myPointer" points to, to the memory address returned by func().

x is a pointer, specifically to an int. So it should be obvious that there are two memory locations used. One for the pointer and one for the memory it's pointing to (assuming the pointer is not null).

The pointer itself holds a memory address, specifically the location of the memory it's pointing to. Something like 0xa456e4fa.

Yes, func() is returning a pointer. The prototype of func would look like the following..

Notice the return type is a pointer to an int. From this and what I said previously, it should be obvious what this will return. Something of the form 0xyyyyyy, or a memory address/pointer. That memory address goes into your x pointer.

Remember that the pointer itself is not holding the data that it's pointing to, it is only the address. There's really no reason you CAN'T return a pointer. However, you do need to be careful in WHAT you return. You do not want to return the address of a local variable because that variable will go out of scope once the function has completed its execution. You'll then be returning the address of something invalid. Returning the VALUE of a local pointer however, is fine because the value you returned (the address) will be preserved as will the memory it's pointing to.

I also just realized I wrote you a book. Damn, I sure do ramble when I'm tired.

MGZero's user avatar

The statement just reads that x is assigned the value returned by function func . For the code to compile without errors , the func should return an address though . And for the code to execute as expected as AlexFZ pointed out , you should take care that func does not return the address of a variable local to the function.

woodstok's user avatar

It means that func() returns a variable of type int*.

Is it eligible to say that we are returning a pointer to x?

No, we are returning a pointer to an integer and assigning it to x since it is a pointer.

This is an example code which returns an int pointer int* func(int a) { int *y = &a; return y; }

cppcoder's user avatar

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged c++ pointers assign or ask your own question .

  • The Overflow Blog
  • The framework helping devs build LLM apps
  • How to bridge the gap between Web2 skills and Web3 workflows
  • Featured on Meta
  • Upcoming initiatives on Stack Overflow and across the Stack Exchange network...
  • Announcing a change to the data-dump process
  • What makes a homepage useful for logged-in users

Hot Network Questions

  • Does the question "will I get transplanted" make sense to your ears?
  • Reorder for smallest largest prefix sum
  • Why is this image from pianochord.org for A11 labeled as an inversion, when its lowest pitch note is an A?
  • How does Biden staying in the presidential race hurt Democrats in Congress?
  • Reducing required length of a mass driver using loop?
  • Are the hangers on these joists sized and installed properly?
  • Can perfectly stable orbits exist in GR?
  • Why can THHN/THWN go in Schedule 40 PVC but NM cable (Romex) requires Schedule 80?
  • Always orient a sundial towards polar north?
  • Were ancient Greece tridents different designs from other historical examples?
  • Narcissist boss won't allow me to move on/sabotaged internal transfer
  • Old client wants files from materials created for them 6 years ago
  • Include clickable 'Fig.'/'Table' in \ref without duplication in captions
  • Is it worth it to apply to jobs that have over 100 applicants or have been posted for few days?
  • Disabling some symbols from being prettified in a given mode
  • Is this circuit safe to put in my ceiling? What improvements could I make?
  • Is "farfel" an idiolectical quirk/part of a familect?
  • What is the meaning of "Mitsuki. Rhymes with nookie."?
  • What is the function of this resistor and capacitor at the input of optoisolator?
  • When Trump ex-rivals, who previously gave Trump terrible comments, now turn to praising him, what benefits could they gain?
  • Examples of distributions with easily solvable quantile functions but hard to solve CDFs
  • What is a good translation for these verbal adjectives? (Greek)
  • Does color temperature limit how much a laser of a given wavelength can heat a target?
  • How important is Waterdeep: Dragon Heist to the story of Waterdeep: Dungeon of the Mad Mage?

assign pointer to object c


  1. Pointers in C/C++ with Examples

    assign pointer to object c

  2. Pointer to Object in C++

    assign pointer to object c

  3. Pointer to Object C++

    assign pointer to object c

  4. How to assign pointer to another pointer in c++

    assign pointer to object c

  5. [Solved] C++ Expression must have pointer-to-object type

    assign pointer to object c

  6. Pointers in C++: The Ultimate Step-by-Step Guide

    assign pointer to object c


  1. C++ Basics For Beginners :: Pointers :: Weekly Tutorials

  2. Pointers to Derived Classes in C++ #42 (Urdu/Hindi)

  3. pointer to class object in c++

  4. C++ Practical

  5. pointer Array C++

  6. what is the pointer variable


  1. Directly assigning values to C Pointers

    You need to create an int variable somewhere in memory for the int * variable to point at. Your second example does this, but it does other things that aren't relevant here. Here's the simplest thing you need to do: int main(){. int variable; int *ptr = &variable; *ptr = 20; printf("%d", *ptr); return 0;

  2. C++ pointer to objects

    Now, pointer and object both are on the stack. Now you can't return this pointer to the outside of the current scope because both allocated memory of the pointer and the object will be freed while stepping outside the scope. So as a summary, option 1 and 3 will allocate an object on the stack while only the option 2 will do it on the heap.

  3. C Pointers

    The use of pointers in C can be divided into three steps: Pointer Declaration. Pointer Initialization. Pointer Dereferencing. 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.

  4. Pointer declaration

    A pointer to function can be initialized with an address of a function. Because of the function-to-pointer conversion, the address-of operator is optional: void f (int);void(* pf1 )(int)=& f;void(* pf2 )(int)= f;// same as &f. Unlike functions, pointers to functions are objects and thus can be stored in arrays, copied, assigned, passed to other ...

  5. Pointer declaration

    Null pointers. Pointers of every type have a special value known as null pointer value of that type. A pointer whose value is null does not point to an object or a function (the behavior of dereferencing a null pointer is undefined), and compares equal to all pointers of the same type whose value is also null.. A null pointer constant can be used to initialize a pointer to null or to assign ...

  6. Pointers

    In general, pointer is a type of a variable that stores a link to another object. In C and C++, the link is the address of that object in the program memory. Pointers allow to refer to the same object from multiple locations of the source code without copying the object. ... If the pointer is const, we can't assign a different address to it ...

  7. Pointers and references to the base class of derived objects

    However, since Derived has a Base part, a more interesting question is whether C++ will let us set a Base pointer or reference to a Derived object. It turns out, we can! ... So even though Derived::getName() shadows (hides) Base::getName() for Derived objects, the Base pointer/reference can not see Derived::getName(). Consequently, they call ...

  8. Base Class Pointer Pointing to Derived Class Object in C++

    Prerequisite: Pointers in C++ A pointer is a data type that stores the address of other data types. Pointers can be used for base objects as well as objects of derived classes. A pointer to the object of the derived class and a pointer to the object of the base class are type-compatible (may be used in different ways).. The pointer of Base Class pointing different objects of the derived class

  9. Pointers to Members

    In C, the comparison function is always passed by pointer (e.g., see the signature to "qsort()"), but in C++ the parameter can come in either as a pointer to function OR as the name of a functor-object, and the result is that sorted containers in C++ can be, in some cases, a lot faster (and never slower) than the equivalent in C.

  10. What is a Pointer to an Object in C++?

    Pointer to object in c++ is defined as the pointer that is used for accessing objects. A pointer is a variable that stores the memory address of another variable. The types of the pointer are Null pointer, Void pointer, Wild pointer, and Dangling pointer. An object is defined as the instance of a class. These objects can access the data members ...

  11. Pointer to Pointer (Double Pointer) in C

    A "pointer to pointer" or a "double pointer" in C behaves just like a normal pointer. So, the size of a double pointer variable is always equal to a normal pointer. We can check it by applying the sizeof operator to the pointers "b" and "c" in the above program −. This shows the equal size of both the pointers −.

  12. 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. We can use a pointer to a pointer to change the values of normal ...

  13. 12.9

    A pointer to a const value (sometimes called a pointer to const for short) is a (non-const) pointer that points to a constant value. To declare a pointer to a const value, use the const keyword before the pointer's data type: int main () { const int x { 5 }; const int* ptr { &x }; // okay: ptr is pointing to a "const int" *ptr = 6; // not ...

  14. c++

    Is there a way to assign the object a pointer variable inside a class of the same name (c++) 0. Assigning pointer classes to new Class, C++. Hot Network Questions Is a "single" cpu safer than multiple cores?

  15. C++ Pointer to Class Members

    datatype class_name::*pointer_name = &class_name::datamember_name ; Using Pointers with Objects. For accessing normal data members we use the dot . operator with object and -> qith pointer to object. But when we have a pointer to data member, we have to dereference that pointer to get what its pointing to, hence it becomes, Object.*pointerToMember

  16. C++ Pointers to Objects

    C++ Pointers to Objects. You can access an object either directly, or by using a pointer to the object. To access an element of an object when using the actual object itself, use the dot operator. To access a specific element of an object when using a pointer to the object, you must use the arrow operator. To declare an object pointer, you use ...

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

    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;

  18. Assigning class objects to pointers

    The point of the program is to: -Open a text file containing data on 10 cars -Read these items into items of Car class type -Assign an array of pointers to correspond to the array of Car items -Sort them based on model -Search the array for a user entered model As you can see, I'm only up to trying to assign the array of pointers to the car ...

  19. C++ Assign Pointer to Pointer

    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, int x; int *ptr1 = &x; /* ptr1 now points to the address of x */. *ptr1 = 7;

  20. How to fix a Windows PC affected by the global outage

    Navigate to the C:\Windows\System32\drivers\CrowdStrike directory. 3. Locate the file matching "C-00000291*.sys" and delete it. 4. Boot the machine normally. Sounds simple, right? But while ...

  21. C++ Pointers

    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. C++. // C++ program to illustrate Pointers #include <bits/stdc++.h> using namespace std; void geeks() { int var = 20; // declare pointer ...

  22. Suspect came within inches of killing Trump, but left few clues as to

    The portrait pieced together so far of the 20-year-old nursing home aide who allegedly tried to assassinate Donald Trump at an election rally reveals frustratingly little about why he would make ...

  23. c++

    Notice the return type is a pointer to an int. From this and what I said previously, it should be obvious what this will return. Something of the form 0xyyyyyy, or a memory address/pointer. That memory address goes into your x pointer. Remember that the pointer itself is not holding the data that it's pointing to, it is only the address.