Sie sind auf Seite 1von 22

10/11/2017 6.

7 Introduction to pointers | Learn C++

6.7 Introduction to pointers


BY ALEX ON JULY 10TH, 2007 | LAST MODIFIED BY ALEX ON APRIL 27TH, 2017

In lesson 1.3 -- a first look at variables, we noted that a variable is a name for a piece of memory that holds a value.
When our program instantiates a variable, a free memory address is automatically assigned to the variable, and any value
we assign to the variable is stored in this memory address.

For example:

1 int x;

When this statement is executed by the CPU, a piece of memory from RAM will be set aside. For the sake of example,
lets say that the variable x is assigned memory location 140. Whenever the program sees the variable x in an expression
or statement, it knows that it should look in memory location 140 to get the value.

The nice thing about variables is that we dont need to worry about what specific memory address is assigned. We just
refer to the variable by its given identifier, and the compiler translates this name into the appropriately assigned memory
address.

However, this approach has some limitations, which well discuss in this and future lessons.

The address-of operator (&)

The address-of operator (&) allows us to see what memory address is assigned to a variable. This is pretty
straightforward:

1 #include <iostream>
2
3 int main()
4 {
5 int x = 5;
6 std::cout << x << '\n'; // print the value of variable x
7 std::cout << &x << '\n'; // print the memory address of variable x
8
9 return 0;
10 }

On the authors machine, the above program printed:

5
0027FEA0

Note: Although the address-of operator looks just like the bitwise-and operator, you can distinguish them because the
address-of operator is unary, whereas the bitwise-and operator is binary.

The dereference operator (*)

Getting the address of a variable isnt very useful by itself.

The dereference operator (*) allows us to get the value at a particular address:

1 #include <iostream>
2
3 int main()
4 {
5 int x = 5;
6 std::cout << x << '\n'; // print the value of variable x

http://www.learncpp.com/cpp-tutorial/67-introduction-to-pointers/ 1/22
10/11/2017 6.7 Introduction to pointers | Learn C++
7 std::cout << &x << '\n'; // print the memory address of variable x
8 std::cout << *&x << '\n'; /// print the value at the memory address of variable x
9
10 return 0;
11 }

On the authors machine, the above program printed:

5
0027FEA0
5

Note: Although the dereference operator looks just like the multiplication operator, you can distinguish them because the
dereference operator is unary, whereas the multiplication operator is binary.

Pointers

With the address-of operator and dereference operators now added to our toolkits, we can now talk about pointers. A
pointer is a variable that holds a memory address as its value.

Pointers are typically seen as one of the most confusing parts of the C++ language, but theyre surprisingly simple when
explained properly.

Declaring a pointer

Pointer variables are declared just like normal variables, only with an asterisk between the data type and the variable
name.

1 int *iPtr; // a pointer to an integer value


2 double *dPtr; // a pointer to a double value
3
4 int* iPtr2; // also valid syntax (acceptable, but not favored)
5 int * iPtr3; // also valid syntax (but don't do this)
6
7 int *iPtr4, *iPtr5; // declare two pointers to integer variables

Syntactically, C++ will accept the asterisk next to the data type, next to the variable name, or even in the middle. Note that
this asterisk is not a dereference. It is part of the pointer declaration syntax.

However, when declaring multiple pointer variables, the asterisk has to be included with each variable. Its easy to forget
to do this if you get used to attaching the asterisk to the type instead of the variable name!

1 int* iPtr6, iPtr7; // iPtr6 is a pointer to an int, but iPtr7 is just a plain int!

For this reason, when declaring a variable, we recommend putting the asterisk next to the variable name.

Best practice: When declaring a pointer variable, put the asterisk next to the variable name.

However, when returning a pointer from a function, its clearer to put the asterisk next to the return type:

1 int* doSomething();

This makes it clear that the function is returning a value of type int* and not an int.

Best practice: When declaring a function, put the asterisk of a pointer return value next to the type.

Just like normal variables, pointers are not initialized when declared. If not initialized with a value, they will contain
garbage.

Assigning a value to a pointer

http://www.learncpp.com/cpp-tutorial/67-introduction-to-pointers/ 2/22
10/11/2017 6.7 Introduction to pointers | Learn C++

Since pointers only hold addresses, when we assign a value to a pointer, that value has to be an address. One of the
most common things to do with pointers is have them hold the address of a different variable.

To get the address of a variable, we use the address-of operator:

1 int value = 5;
2 int *ptr = &value; // initialize ptr with address of variable value

Conceptually, you can think of the above snippet like this:

This is where pointers get their name from -- ptr is holding the address of variable value, so we say that ptr is pointing to
value.

It is also easy to see using code:

1 #include <iostream>
2
3 int main()
4 {
5 int value = 5;
6 int *ptr = &value; // initialize ptr with address of variable value
7
8 std::cout << &value << '\n'; // print the address of variable value
9 std::cout << ptr << '\n'; // print the address that ptr is holding
10
11 return 0;
12 }

On the authors machine, this printed:

0012FF7C
0012FF7C

The type of the pointer has to match the type of the variable being pointed to:

1 int iValue = 5;
2 double dValue = 7.0;
3
4 int *iPtr = &iValue; // ok
5 double *dPtr = &dValue; // ok
6 iPtr = &dValue; // wrong -- int pointer cannot point to the address of a double variable
7 dPtr = &iValue; // wrong -- double pointer cannot point to the address of an int variable

Note that the following is also not legal:

1 int *ptr = 5;

This is because pointers can only hold addresses, and the integer literal 5 does not have a memory address. If you try
this, the compiler will tell you it cannot convert an integer to an integer pointer.

C++ will also not allow you to directly assign literal memory addresses to a pointer:

http://www.learncpp.com/cpp-tutorial/67-introduction-to-pointers/ 3/22
10/11/2017 6.7 Introduction to pointers | Learn C++
1 double *dPtr = 0x0012FF7C; // not okay, treated as assigning an integer literal

The address-of operator returns a pointer

Its worth noting that the address-of operator (&) doesnt return the address of its operand as a literal. Instead, it returns a
pointer containing the address of the operand, whose type is derived from the argument (e.g. taking the address of an int
will return the address in an int pointer).

We can see this in the following example:

1 #include <iostream>
2 #include <typeinfo>
3
4 int main()
5 {
6 int x(4);
7 std::cout << typeid(&x).name();
8
9 return 0;
10 }

On Visual Studio 2013, this printed:

int *

(With gcc, this prints pi (pointer to integer) instead).

This pointer can then be printed or assigned as desired.

Dereferencing pointers

Once we have a pointer variable pointing at something, the other common thing to do with it is dereference the pointer to
get the value of what its pointing at. A dereferenced pointer evaluates to the contents of the address it is pointing to.

1 int value = 5;
2 std::cout << &value; // prints address of value
3 std::cout << value; // prints contents of value
4
5 int *ptr = &value; // ptr points to value
6 std::cout << ptr; // prints address held in ptr, which is &value
7 std::cout << *ptr; // dereference ptr (get the value that ptr is pointing to)

The above program prints:

0012FF7C
5
0012FF7C
5

This is why pointers must have a type. Without a type, a pointer wouldnt know how to interpret the contents it was
pointing to when it was dereferenced. Its also why the type of the pointer and the variable address its being assigned to
must match. If they did not, when the pointer was dereferenced, it would misinterpret the bits as a different type.

Once assigned, a pointer value can be reassigned to another value:

1 int value1 = 5;
2 int value2 = 7;
3
4 int *ptr;
5
http://www.learncpp.com/cpp-tutorial/67-introduction-to-pointers/ 4/22
10/11/2017 6.7 Introduction to pointers | Learn C++
6 ptr = &value1; // ptr points to value1
7 std::cout << *ptr; // prints 5
8
9 ptr = &value2; // ptr now points to value2
10 std::cout << *ptr; // prints 7

When the address of variable value is assigned to ptr, the following are true:

ptr is the same as &value


*ptr is treated the same as value

Because *ptr is treated the same as value, you can assign values to it just as if it were variable value! The following
program prints 7:

1 int value = 5;
2 int *ptr = &value; // ptr points to value
3
4 *ptr = 7; // *ptr is the same as value, which is assigned 7
5 std::cout << value; // prints 7

A warning about dereferencing invalid pointers

Pointers in C++ are inherently unsafe, and improper pointer usage is one of the best ways to crash your application.

When a pointer is dereferenced, the application attempts to go to the memory location that is stored in the pointer and
retrieve the contents of memory. For security reasons, modern operating systems sandbox applications to prevent them
from improperly interacting with other applications, and to protect the stability of the operating system itself. If an
application tries to access a memory location not allocated to it by the operating system, the operating system may shut
down the application.

The following program illustrates this, and will probably crash when you run it (go ahead, try it, you wont harm your
machine):

1 #include <iostream>
2
3 void foo(int *&p)
4 {
5 }
6
7 int main()
8 {
9 int *p; // Create an uninitialized pointer (that points to garbage)
10 foo(p); // Trick compiler into thinking we're going to assign this a valid value
11
12 std::cout << *p; // Dereference the garbage pointer
13
14 return 0;
15 }

The size of pointers

The size of a pointer is dependent upon the architecture the executable is compiled for -- a 32-bit executable uses 32-bit
memory addresses -- consequently, a pointer on a 32-bit machine is 32 bits (4 bytes). With a 64-bit executable, a pointer
would be 64 bits (8 bytes). Note that this is true regardless of what is being pointed to:

1 char *chPtr; // chars are 1 byte


2 int *iPtr; // ints are usually 4 bytes
3 struct Something
4 {
5 int nX, nY, nZ;
6 };
7 Something *somethingPtr; // Something is probably 12 bytes

http://www.learncpp.com/cpp-tutorial/67-introduction-to-pointers/ 5/22
10/11/2017 6.7 Introduction to pointers | Learn C++
8
9 std::cout << sizeof(chPtr) << '\n'; // prints 4
10 std::cout << sizeof(iPtr) << '\n'; // prints 4
11 std::cout << sizeof(somethingPtr) << '\n'; // prints 4

As you can see, the size of the pointer is always the same. This is because a pointer is just a memory address, and the
number of bits needed to access a memory address on a given machine is always constant.

What good are pointers?

At this point, pointers may seem a little silly, academic, or obtuse. Why use a pointer if we can just use the original
variable?

It turns out that pointers are useful in many different cases:

1) Arrays are implemented using pointers. Pointers can be used to iterate through an array (as an alternative to array
indices) (covered in lesson 6.8).
2) They are the only way you can dynamically allocate memory in C++ (covered in lesson 6.9). This is by far the most
common use case for pointers.
3) They can be used to pass a large amount of data to a function in a way that doesnt involve copying the data, which is
inefficient (covered in lesson 7.4)
4) They can be used to pass a function as a parameter to another function (covered in lesson 7.8).
5) They can be used to achieve polymorphism when dealing with inheritance (covered in lesson 12.1).
6) They can be used to have one struct/class point at another struct/class, to form a chain. This is useful in some more
advanced data structures, such as linked lists and trees.

So there are actually a surprising number of uses for pointers. But dont worry if you dont understand what most of these
are yet. Now that you understand what pointers are at a basic level, we can start taking an in-depth look at the various
cases in which theyre useful, which well do in subsequent lessons.

Conclusion

Pointers are variables that hold a memory address. They can be dereferenced using the dereference operator (*) to
retrieve the value at the address they are holding. Dereferencing a garbage pointer may crash your application.

Best practice: When declaring a pointer variable, put the asterisk next to the variable name.
Best practice: When declaring a function, put the asterisk of a pointer return value next to the type.

Quiz

1) What values does this program print? Assume a short is 2 bytes, and a 32-bit machine.

1 short value = 7; // &value = 0012FF60


2 short otherValue = 3; // &otherValue = 0012FF54
3
4 short *ptr = &value;
5
6 std::cout << &value << '\n';
7 std::cout << value << '\n';
8 std::cout << ptr << '\n';
9 std::cout << *ptr << '\n';
10 std::cout << '\n';
11
12 *ptr = 9;
13
14 std::cout << &value << '\n';
15 std::cout << value << '\n';
16 std::cout << ptr << '\n';
17 std::cout << *ptr<< '\n';
18 std::cout << '\n';
19

http://www.learncpp.com/cpp-tutorial/67-introduction-to-pointers/ 6/22
10/11/2017 6.7 Introduction to pointers | Learn C++
20 ptr = &otherValue;
21
22 std::cout << &otherValue << '\n';
23 std::cout << otherValue << '\n';
24 std::cout << ptr << '\n';
25 std::cout << *ptr << '\n';
26 std::cout << '\n';
27
28 std::cout << sizeof(ptr) << '\n';
29 std::cout << sizeof(*ptr) << '\n';

Show Solution

2) Whats wrong with this snippet of code?

1 int value = 45;


2 int *ptr = &value; // declare a pointer and initialize with address of value
3 *ptr = &value; // assign address of value to ptr

Show Solution

6.7a -- Null pointers

Index

6.6 -- C-style strings

Share this:

Facebook Twitter Google Pinterest 1

Ad

Findchips Pro

Visit Site

C++ TUTORIAL | PRINT THIS POST

http://www.learncpp.com/cpp-tutorial/67-introduction-to-pointers/ 7/22
10/11/2017 6.7 Introduction to pointers | Learn C++

119 comments to 6.7 Introduction to pointers

Older Comments 1 2

heyjuhua
September 17, 2017 at 9:00 am Reply

Hi, Alex, may I ask are you going to teach us


6) They can be used to have one struct/class point at another struct/class, to form a chain. This is useful
in some more advanced data structures, such as linked lists and trees.

this kind of knowledge? if not do you have any recommendation of a book or good resource to learn about because I
think the way you explain the knowledge is very easy to follow and understand! thanks

Alex
September 17, 2017 at 2:19 pm Reply

I dont have anything on advanced data structures at this point. Id like to add some lessons at
some point, but it probably wont happen soon. I dont know of any good books that make these
things easy to learn either -- which is why Id like to write it.

muki
August 27, 2017 at 11:39 pm Reply

could you Please explain in details below code :

#include <iostream>

void foo(int *&p)


{
}

int main()
{
int *p; // Create an uninitialized pointer (that points to garbage)
foo(p); // Trick compiler into thinking were going to assign this a valid value

std::cout << *p; // Dereference the garbage pointer

return 0;
}

Alex
August 28, 2017 at 5:07 pm Reply

Were passing pointer p by reference to function foo() (we havent covered references yet at this
point). Even though we never do anything with p inside function foo(), this is often enough to work
around the compilers basic uninitialized variable detection.

Nguyen
July 27, 2017 at 9:16 am Reply

Hi Alex,

The address-of operator (&)

http://www.learncpp.com/cpp-tutorial/67-introduction-to-pointers/ 8/22
10/11/2017 6.7 Introduction to pointers | Learn C++

The address-of operator (&) allows us to see what memory address is assigned to a variable. This is pretty
straightforward:

#include <iostream>

int main()
{
int x = 5;
std::cout << x << \n; // print the value of variable x
std::cout << &x << \n; // print the memory address of variable x

return 0;
}

=================================================
4 bytes of memory is reserved for the variable x. Each byte of memory has a unique address. Lets name these
addresses as address0, address1, address2, & address3. How do I know which address should be printed?

Alex
July 27, 2017 at 9:53 pm Reply

The lowest address of a multi-byte variable is returned. So in your example, address0 would be
returned (assuming address 0, 1, 2, and 3 are sequential).

Jack
July 24, 2017 at 9:09 am Reply

Hi Alex,

Any chance to recommend some good pointer practice website in c++? Love your quiz and please keep up the good
work!

Alex
July 24, 2017 at 2:55 pm Reply

Sorry, I dont have any recommendations in this regard.

Nguyen
July 13, 2017 at 2:51 pm Reply

Hi Alex,

I have a very silly question. Are memory address & memory location the same?

Thanks, Have a great day

Alex
July 13, 2017 at 3:09 pm Reply

Yep.

Nguyen
July 13, 2017 at 8:55 am Reply

Hi Alex,
http://www.learncpp.com/cpp-tutorial/67-introduction-to-pointers/ 9/22
10/11/2017 6.7 Introduction to pointers | Learn C++

Quiz 1.

*ptr = 9; //Line 12
Is it Ok if I assign otherValue to *ptr (*ptr = otherValue)?

Quiz 2.

*ptr = &value; // assign address of value to ptr


Anything wrong if I just assign value instead of &value to *prt (*ptr = value;)

Thanks, Have a great day.

Alex
July 13, 2017 at 10:46 am Reply

1) Yes.
2) It depends. ptr = &value sets ptr to point at the address of value. *ptr = value means copy
value into whatever address ptr is pointing at. If ptr is already pointing at value, then this is the equivalent of
value = value, which is useless.

Nguyen
July 13, 2017 at 1:18 pm Reply

This means I can assign a variable to a dereferenced pointer. That variable must be
initialized with a value; otherwise, the dereferenced pointer is a garbage. Please let me
know if I am wrong (sorry for my poor English)

Example 1:

int x = 1;
int y = 2;

int *ptr = &x;

*ptr = y;
std::cout << *ptr; // prints 2

==============================

Example 2:

int x = 1;
int y; // y is not initialized

int *ptr = &x;

*ptr = y;
std::cout << *ptr; // Dereference the garbage pointer

Alex
July 13, 2017 at 3:09 pm Reply

Right. A dereference pointer acts just like a normal variable (assuming the dereference
is successful). Assigning a garbage value to a dereferenced pointer has the same
effect as assigning a garbage value to a normal variable.

lnm
June 26, 2017 at 10:50 pm Reply
http://www.learncpp.com/cpp-tutorial/67-introduction-to-pointers/ 10/22
10/11/2017 6.7 Introduction to pointers | Learn C++

Hey, Alex!
Can c++ swap the value of 2 pointer or use std::sort to sort linked lists ?
If yes, can you illustrate it for me.
Thanks.

Alex
June 27, 2017 at 9:59 pm Reply

Yes, you can swap the value of two pointers in two ways:
1) using std::swap from the standard library
2) by writing your own function, and passing your pointers by reference (this is covered in lesson 7.4)

You cant sort a linked list using std::sort because std::sort requires the class being sorted has a random
access iterator, and std::list only has bidirectional iterators. However, std::list have their own sort method as
part of the class, so you can use that.

lnm
June 28, 2017 at 5:01 am Reply

Thanks Alex.

Mr C++
June 16, 2017 at 2:44 am Reply

1 int main() {
2 int x = 5;
3 int *ptr = &x;
4 std::cout << ptr<< " "<< &ptr;
5 return 0;
6 }

This Prints :-
0x60ff1c 0x60ff18

1 #include<iostream>
2 int main() {
3 int x = 5;
4 int *ptr = &x;
5 std::cout << ptr;
6 return 0;
7 }

This Prints :-
0x60ff18

Why does "ptr" prints 2 different memory addresses while pointing to the same variable?
And Also, why &ptr in the 1st case == ptr in the 2nd case?
(I know that &ptr prints the memory address of the pointer(not the variable it is pointing to).

Alex
June 16, 2017 at 8:31 am Reply

No idea. Maybe your compiler is optimizing the code differently in each case.

http://www.learncpp.com/cpp-tutorial/67-introduction-to-pointers/ 11/22
10/11/2017 6.7 Introduction to pointers | Learn C++

Mr C++
June 16, 2017 at 8:34 am Reply

Ok Man !

Sivasankar
June 25, 2017 at 5:11 am Reply

Why does "ptr" prints 2 different memory addresses while pointing to the same
variable?
Because you are printing the value of the pointer variable ptr(i.e. the address of variable x) and the
address of pointer itself(i.e. &ptr). Obviously they are 2 different addresses and will be different.

why &ptr in the 1st case == ptr in the 2nd case?


There will be no logical connection between the addresses of variables in different runs. In the first
case, compiler assigned memory address 0x60ff18 to ptr. Then it got released(i.e. it is available for
use by other programs) at the end of the main in first run. In the second case, compiler reused the
address 0x60ff18 for variable x which is free at that time.

Mr C++
June 25, 2017 at 6:15 am Reply

I think you misunderstood my question !


Even if I do :-

1 std::cout << ptr <<" " << &ptr;

It prints the same memory address for both !


I hope you must have understood by now !
Thank Anyway

Sivasankar
June 25, 2017 at 6:36 am Reply

Hi. I understood your code. It should print different addresses. Here,


remember that ptr is also a variable like x is a variable. Every variable has its
own address. Syntactically,

&<variable name> = address of <variable name>


<variable name> = value held by the <variable name>

1 std::cout << ptr << " " << &ptr;

In above line, as per type and definition, ptr refers to the address held by ptr which is the
address of variable x.
we can see that as below

ptr = value of variable ptr = address of x = &x


*ptr = value at the address held by ptr = value at &x = 5
x = value of variable x = 5
&x = address of variable x
*x = invalid statement

&ptr = address of variable ptr.

Even though ptr is pointing to x, ptr should have its own address. so &x != &ptr implies
ptr != &ptr
http://www.learncpp.com/cpp-tutorial/67-introduction-to-pointers/ 12/22
10/11/2017 6.7 Introduction to pointers | Learn C++

Mr C++
June 25, 2017 at 12:33 pm Reply

I knew this man !


I was just asking Alex that why is ptr and &ptr printing same memory
address. That was my only Question.
Thanks For The Help Anyways

Sivasankar
June 25, 2017 at 11:28 pm

Your concern might be why &ptr in the 1st output (0x60ff18) is


same as ptr in the 2nd output (0x60ff18). Is that your question? If
so, please check my comments below

They are 2 different runs of the program. This is how it might happened in step
by step,

1. In the 1st run, compiler allocated 0x60ff1c to int variable x and 0x60ff18 to
pointer variable ptr.
2. So below line printed "0x60ff1c 0x60ff18"

1 std::cout << ptr<< " "<< &ptr;

3. While exiting the main function here, both the int variable x and the pointer
variable ptr are automatically destroyed. So their addresses (0x60ff1c and
0x60ff18) are not allocated anymore and free for reuse.
4. In 2nd time, compiler reused the address 0x60ff18 and allocated to variable
x (Here, the same address 0x60ff18 was once allocated to ptr at step 1 in 1st
run and then got released run at step 3 in 1st run) and some other free address
to pointer variable ptr.
5. So below line printed "0x60ff18"

1 std::cout << ptr; // here, ptr = &x; as per the code

Ignore it if it is not your question

Said
April 27, 2017 at 7:11 pm Reply

Finally, I was wondering how you could pass variables in to a function like switch and have it violate
scope. I tried to do this back in lesson 6.4 but I couldnt figure it out but now

1 #include <iostream>
2
3 using namespace std;
4
5 void swit(int &x, int &y)
6 {
7 int intermediate = x;
8 x = y;
9 y = intermediate;
10 }
11
12 int main()
13 {

http://www.learncpp.com/cpp-tutorial/67-introduction-to-pointers/ 13/22
10/11/2017 6.7 Introduction to pointers | Learn C++
14 int x = 5;
15 int y = 9;
16
17 cout << x << " " << y << '\n';
18
19 swit(x, y);
20
21 cout << x << " " << y << '\n';
22
23 return 0;
24 }

Said
May 5, 2017 at 7:45 pm Reply

Never mind, just got to references these are not pointers. Was wondering why this worked
exactly because the & operator gives the the address and doesnt assign it.

Kris
April 27, 2017 at 2:38 am Reply

Hi, nice tutorial. I would just like to point out (with pointer of course ) that maybe you should comment
how these two lines which are identical at first are really not identical at all. It got me a bit confused, but
then I remembered that * can be anywhere between type and actual name of pointer so my conclusion is that this line
"2." can/must be observed as line "2.". The lines Im talking about are:

1 /* 1. */ int value = 45; // declaration and initialization of variable


2 /* 2. */ int *pointer = &value;// declaration and initialization of pointer, pointer poin
ts to address of var. value
3 /* some code... */
4 /* 3. */ *pointer = &value // error: invalid conversion from 'int*' to 'int'

So maybe You should just point out that while declaring pointer this * is part of cast and that is is actually (in logical
sense) something like this:

1 /* 2'. */ (int*) pointer = &value;

I hope You understood what I was trying to say and if I am wrong please correct me.

Thanks & best regards!


Kris

Alex
April 27, 2017 at 5:12 pm Reply

I get what you mean, and I can see why this is confusing. I hope you dont mind, but I turned your
example into a quiz question, complete with a detailed explanation. Hopefully this will help others
who run across a similar confusion.

Kris
April 27, 2017 at 10:57 pm Reply

Of course I dont mind, this was what i was getting at.

Thanks for this comprehensive and useful tutorial!!

http://www.learncpp.com/cpp-tutorial/67-introduction-to-pointers/ 14/22
10/11/2017 6.7 Introduction to pointers | Learn C++

James Ray
April 23, 2017 at 1:24 am Reply

"This is because pointers can only hold addresses, and the integer literal 5 does not have a memory
address." Should you say: "the integer literal 5 is not a memory address." I am surprised if it doesnt
have a memory address. How would the CPU, which can only read 1s and 0s (or electrical binary states), be able to
know what 5 represents, if it isnt stored in memory with the compiler? I suspect that this semi-rhetorical question is
not fully correct, thats just where my understanding is. I guess this may be beyond the scope of C++ as well, but it is
probably more important to have at least a basic, high-level understanding of how CPUs, memory and computers work
before learning a programming language.

http://homepage.cs.uri.edu/faculty/wolfe/book/Readings/Reading04.htm
http://www.computerhope.com/jargon/m/memory.htm

Alex
April 23, 2017 at 2:07 pm Reply

The literal 5 both doesnt have an assigned memory address, nor is it a memory address, so both
of our statements are true. While its true that 5 will get turned into a series of bits that will go into
memory somewhere (as every instruction and piece of data has to be in memory to be executed), that memory
is transient. Generally, when we say something has a memory address, we mean a particular spot of memory
has been reserved for it (basically, its an l-value). With a value like 5, thats not true -- its just a transient value.
You cant ask 5 for its memory address (like you can with a variable) and get an address back.

James Ray
April 24, 2017 at 2:36 am Reply

Yeah, that makes sense. The value of 5, being fixed, cant be an l-value, so it doesnt and
shouldnt have a memory address.

Rohit
March 9, 2017 at 7:37 am Reply

This code is printing 8 instead of 4, why?

char *chPtr; // chars are 1 byte


int *iPtr; // ints are usually 4 bytes
struct Something
{
int nX, nY, nZ;
};
Something *somethingPtr; // Something is probably 12 bytes

std::cout << sizeof(chPtr) << \n; // prints 4


std::cout << sizeof(iPtr) << \n; // prints 4
std::cout << sizeof(somethingPtr) << \n; // prints 4

Rohit
March 9, 2017 at 12:57 pm Reply

Got the answer, no need to reply.

http://www.learncpp.com/cpp-tutorial/67-introduction-to-pointers/ 15/22
10/11/2017 6.7 Introduction to pointers | Learn C++

Alex
March 9, 2017 at 2:58 pm Reply

Pointers hold memory addresses. So the size of a pointer will always be equal to the size of a
memory address on your system. On a 32-bit operating system, that will generally be 32 bits (4
bytes), which is why youre seeing all of these print 4. On a 64-bit operating system, this will generally be 64
bits (8 bytes).

Rohit
March 9, 2017 at 7:21 am Reply

Hi Alex!
Didnt get this code. Why you used ptr = &value instead of *ptr = &value?
int value1 = 5;
int value2 = 7;

int *ptr;

ptr = &value1; // ptr points to value1


std::cout << *ptr; // prints 5

ptr = &value2; // ptr now points to value2


std::cout << *ptr; // prints 7

Alex
March 9, 2017 at 2:57 pm Reply

Remember, pointers hold addresses. So when we set a pointers value, we need to give it an
address. We can get the address of a normal variable using &.

ptr = &value1 means get value1s address and assign it to ptr, which makes sense since pointers hold
addresses.

Dereferencing a pointer (via *) means get the value that the pointer is pointing to.

*ptr = &value1 means get value1s address and assign it to the value that ptr is pointing to. ptr is pointing to
an integer, so *ptr refers to the integers value. It doesnt make sense to assign the address of value1 to an
integer value.

Matheus
March 8, 2017 at 4:57 pm Reply

What this piece of code means?

1 int main()
2 {
3 int value = 7;
4 int *ptr = &value;
5
6 cout << ptr << endl;
7 cout << &ptr << endl;
8 }

Is &ptr returning the address of the pointer variable? Pointers are memory address that allocate other memory
address (which are pointers too)?

http://www.learncpp.com/cpp-tutorial/67-introduction-to-pointers/ 16/22
10/11/2017 6.7 Introduction to pointers | Learn C++

Alex
March 8, 2017 at 8:41 pm Reply

&ptr would return the address of ptr. Pointers arent memory addresses, nor do they allocate
other memory addresses in and of themselves.

Pointers are essentially normal variable that hold addresses instead of normal values. Those addresses can be
the addresses of other variables, or to dynamically allocated memory.

Elithrion
February 28, 2017 at 3:12 pm Reply

I tried your "dereference an uninitialized pointer" example with MinGW (from inside Eclipse for what
thats worth), and was disappointed to find that it didnt crash - instead it output a consistent (though
garbage) value on every run. Not only that, but it also compiled without the foo() function trick with only a warning.

It took 3-6 iterations through my loop (consistent number for one build, different between slightly different builds)
before it finally started behaving itself and crashing as it should:

1 const int count = 100;


2 int * pointers[count];
3 for (int i = 0; i < count; i++)
4 std::cout << *pointers[i] << std::endl;

Also, this:

1 for (int i = 0; i < 1000; i++)


2 {
3 int *p;
4 std::cout << *p << std::endl;
5 }

Prints the same number over and over (presumably moved initialization out of loop while compiling for efficiency).

And this:

1 for (int i = 0; i < 1000; i++)


2 {
3 int *p;
4 std::cout << *p << std::endl;
5 p++;
6 }

Prints varying numbers, usually crashing, but sometimes not (and in all cases running for many iterations unlike the
array version). Im kinda curious what the compiler is doing

Paul
February 3, 2017 at 12:52 pm Reply

Seems like you have missed "0x" in the example of assigning value to a pointer, because 0012FF7C will
be interpreted like octal constant.

Alex
February 3, 2017 at 5:10 pm Reply

Thanks for pointing that out, fixed!

http://www.learncpp.com/cpp-tutorial/67-introduction-to-pointers/ 17/22
10/11/2017 6.7 Introduction to pointers | Learn C++

Roy
January 19, 2017 at 11:27 am Reply

Just a quick suggestion. I was wondering if it was possible to use uniform initialization with pointers, so I
tried it and it worked. Perhaps it might be a good idea to include a remark about this in the tutorial.

Tyler
December 19, 2016 at 9:24 pm Reply

Hello, first of all thanks for the great tutorial. I dont know if you still maintain this website but I had a
question that I couldnt easily find on the web. What is the value returned when I use address-of operator
on a defined pointer?

Suppose I had the following code:

1 int x = 5;
2 int *ptr = &x;
3 std::cout << ptr << 'n';
4 std::cout << &ptr << 'n';

Im unsure what the address in the second print statement refers do. Is it possible for the memory address to have an
address of itself? Or is it the address of the integer literal assigned to ptr in the form of memory address? Or is it
something completely different?

Edit: I just tried printing them out with typeid() and &ptr prints as int * * which I guess makes sense semantically
But conceptually I have no clue what the hell is going on lol So it does seem like the memory address has its own
address, I think, but does that also explain why the two addresses (ptr and &ptr) are off by 32 bits at most? What is
this uh address of address of a pointer business?

Alex
December 20, 2016 at 12:49 pm Reply

Okay, let me see if I can clarify whats going on. Memory addresses are just memory address,
theres nothing special there.

All variables are assigned a memory address. So when you declare int x, variable x gets a memory address
(lets say address 10). When you declare int *ptr, variable ptr gets a memory address (lets say address 20).

Now, because youve initialized ptr with the address of x (10), the value placed in ptrs memory address (20)
will be xs address (10).

So, our memory looks like this:


Address Value Note
10 5 int x
20 10 int *ptr

Now, lets take a look at 3 different print statements:

1 std::cout << *ptr; // print the value at the address that ptr is pointing to.ptr is
pointing to address 10.The value at address 10 is 5, so this prints 5.
2 std::cout << ptr; // print the value of ptr itself.ptr is holding value 10, so this
3 would print 10.
std::cout << &ptr; // this the address of ptr itself.ptr was assigned address 20, s
o this would print 20.

Tyler
December 20, 2016 at 3:58 pm Reply

http://www.learncpp.com/cpp-tutorial/67-introduction-to-pointers/ 18/22
10/11/2017 6.7 Introduction to pointers | Learn C++

Oh, thank you that clarifies everything. You sure are a great teacher.

Klarslan
September 27, 2016 at 12:39 pm Reply

Best explanation I have ever seen.

bert
September 10, 2016 at 11:35 am Reply

Typo:

Pointer variables are declared just like normal variable,

I believe you meant to type "normal variables"

Pascal Kangberee
September 7, 2016 at 5:11 am Reply

Thank a lot. Finally understand pointers. Great job

Dragos
September 4, 2016 at 2:59 am Reply

I have something unclear here:

1 #include <iostream>
2
3 void foo(int *&p)
4 {
5 }
6
7 int main()
8 {
9 int *p; // Create an uninitialized pointer (that points to garbage)
10 foo(p); // Trick compiler into thinking we're going to assign this a valid value
11
12 std::cout << *p; // Dereference the garbage pointer
13
14 return 0;
15 }

the fuction has int *&p, but I tought when we use * with int we declare a pointer variable, so the name of the variable is
"&p"? If not what that does mean? I hope you understand what I mean.

Alex
September 4, 2016 at 7:10 pm Reply

The & in the context of a function parameter means reference, not address-of. Well cover
references shortly.

Abdul sami

http://www.learncpp.com/cpp-tutorial/67-introduction-to-pointers/ 19/22
10/11/2017 6.7 Introduction to pointers | Learn C++

August 3, 2016 at 6:17 am Reply

Dear Alex ,I hope you will be fine.

I have a question about Arrays.

If we declare an Array of any size for example

1 int arr[6]={2,3,6,8,1,9};

Now arr will become a pointer point to the first element of arr[6].

Now when we find the size arr

1 std::cout<<"Size of Array = "<<sizeof(arr);

//Size of Array = 6

why this is happening, the arr is an int type pointer point to the first element
same problem in function argument

Alex
August 3, 2016 at 2:23 pm Reply

arr doesnt decay into a pointer when used with operator sizeof(), so sizeof() is able to access the
array length.

The size of the array isnt 6, its 24 (6 elements * 4 bytes each).

abolfazl
July 7, 2016 at 12:03 am Reply

1 #include<iostream>
2 using namespace std;
3
4 int main()
5 {
6 int num=913;
7 int *ptr1;
8 int **ptr2;
9 int ***ptr3;
10 ptr1=&num;
11 ptr2=&ptr1;
12 ptr3=&ptr2;
13 cout<<*ptr1<<endl ; //*ptr1
14 cout<<ptr1<<endl; //&ptr1
15 cout<<**ptr2<<endl ;//*ptr2
16 cout<<ptr2<<endl; //&ptr2
17 cout<<***ptr3<<endl ; //*ptr3
18 cout<<ptr3<<endl; //&ptr3
19
20
21 }

Georges Theodosiou
June 27, 2016 at 4:34 am Reply

Mr Alex,
Please permit me a comment: At http://www.tutorialspoint.com/cplusplus/cpp_pointers.htm , first
http://www.learncpp.com/cpp-tutorial/67-introduction-to-pointers/ 20/22
10/11/2017 6.7 Introduction to pointers | Learn C++

sentence is:
"C++ pointers are easy and fun to learn." I study c++ pointers for several days and feel that you are right on that:
"Pointers are typically seen as one of the most confusing parts of the C++ language, but theyre surprisingly simple
when explained properly.".
I express my sincere gratitude for this sentence.

With regards and friendship


Georges Theodosiou

Prajwal
June 19, 2016 at 4:46 am Reply

Hey Alex,
That was yet another great tut indeed!
Ive got a doubt !
When I output an address of a number,say 5 using &value,
This is what I get : 0x22ff44
But above for the address of 5 ,youve given this : 0012FF7C

May I know whats the difference b/w those if you dont mind ?

Waiting for your reply,


Prajwal

Alex
June 20, 2016 at 12:56 pm Reply

Just different addresses in memory. Mine appear to be padded to 32-bits with leading zeroes,
whereas yours arent.

Georges Theodosiou
June 16, 2016 at 1:24 am Reply

Mr Alex,
Please permit me one more comment about address of variables value. When I posted massage by
June 11, I was using Ubuntu. Now I use Windows and address changes when I run program again, and indeed when
change variables type or name or value. Also new address is 4 bytes different than previous when type is "int" as you
posted by June 10. So you are right on that it depends on the platform used. I have learned also this from you. Many
thanks. I have to learn many from you about c++. Regards.

Older Comments 1 2

1 Best Website Templates 3 Software Developer Career

2 Java Programmer Jobs 4 Computer Science Books

http://www.learncpp.com/cpp-tutorial/67-introduction-to-pointers/ 21/22
10/11/2017 6.7 Introduction to pointers | Learn C++

http://www.learncpp.com/cpp-tutorial/67-introduction-to-pointers/ 22/22

Das könnte Ihnen auch gefallen