Sie sind auf Seite 1von 5

c - What does "dereferencing" a pointer mean? - S...

http://stackoverow.com/questions/4955198/what...

sign up

Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no
registration required.

log in

tour

help

careers 2.0

Take the 2-minute tour

What does dereferencing a pointer mean?

What does it mean to dereference a pointer? Can I please get a explanation with an example?
c

pointers

dereference

edited Feb 10 '11 at 9:32


Cody Gray
94.5k 11 153 242

asked Feb 10 '11 at 9:16


asir
750 3 11 13

this can help you: stackoverflow.com/questions/2795575/ Harry Joy Feb 10 '11 at 9:17

cslibrary.stanford.edu/106 Erik Feb 10 '11 at 9:18

int *p; would define a pointer to an integer, and *p would dereference that pointer, meaning that it would
actually retrieve the data that p points to. Peyman Feb 10 '11 at 9:21

Binky's Pointer Fun (cslibrary.stanford.edu/104) is a GREAT video about pointers that might clarify things.
@Erik- You rock for putting up the Stanford CS Library link. There are so many goodies there...
templatetypedef Feb 10 '11 at 9:27

Harry's response is the opposite of helpful here. Jim Balter Feb 10 '11 at 9:39

5 Answers

Reviewing the basic terminology


(Using terminology a bit loosely to make it easier to understand...)
A pointer contains a number identifying a memory address, with:
0 referring to the first byte in the process memory / address space,
1 is the second byte, and so on....
When you want to access the data/value in the memory that the pointer points to - the contents of the
address with that numerical index - then you dereference the pointer.
Different computer languages have different notations to tell the compiler or interpreter that you're now
interested in the pointed-to value - I focus below on C and C++.

A pointer scenario
Consider in C, given a pointer such as p below...
const char* p = "abc";
...four bytes with the numerical values used to encode the letters 'a', 'b', 'c', and a 0 byte to denote the end of
the textual data, are stored somewhere in memory and the numerical address of that data is stored in p .
For example, if the string literal happened to be at address 0x1000 and p a 32-bit pointer at 0x2000, the
memory content would be:
Memory Address (hex)

1 of 5

Variable name

Contents

04/04/2014 03:35 PM

c - What does "dereferencing" a pointer mean? - S...


1000
1001
1002
1003
...
2000-2003

http://stackoverow.com/questions/4955198/what...

'a' == 97 (ASCII)
'b' == 98
'c' == 99
0
p

1000 hex

Note that there is no variable name/identifier for address 0x1000, but we can indirectly refer to the string
literal using a pointer storing its address: p .

Dereferencing the pointer


To refer to the characters p points to we dereference p using one of these notations (again, for C):
assert(*p == 'a'); // the first character at address p will be 'a'
assert(p[1] == 'b'); // p[1] actually dereferences a pointer created by adding
// p and 1 times the size of the things to which p points:
// in this case they're char which are 1 byte in C...
assert(*(p + 1) == 'b'); // another notation for p[1]
You can also move pointers through the pointed-to data, dereferencing them as you go:
++p; // increment p so it's now 0x1001
assert(*p == 'b'); // p == 0x1001 which is where the 'b' is...
If you have some data that can be written to, then you can do things like this:
int x = 2;
int* p_x = &x; // put the address of the x variable into the pointer p_x
*p_x = 4;
// change the memory at the address in p_x to be 4
assert(x == 4); // check x is now 4
Above, you must have known at compile time that you would need a variable called x , and the code asks
the compiler to arrange where it should be stored, ensuring the address will be available via &x .

Dereferencing and accessing a structure data member


In C, if you have variable that is a structure with data members, you can access those members using the
-> dereferencing operator:
typedef struct X { int i_; double d_; } X;
X x;
X* p = &x;
p->d_ = 3.14159; // dereference and access data member x.d_
(*p).d_ *= -1;
// another equivalent notation for accessing x.d_

Multi-byte data types


To use a pointer, a computer program also needs some insight into the type of data that is being pointed at if that data type needs more than one byte to represent, then the pointer normally points to the lowestnumbered byte in the data.
So, looking at a slightly more complex example:
double sizes[] = { 10.3, 13.4, 11.2, 19.4 };
double* p = sizes;
assert(p[0] == 10.3); // knows to look at all the bytes in the first double value
assert(p[1] == 13.4); // actually looks at bytes from address p + 1 * sizeof(double)
// (sizeof(double) is almost always eight bytes)
assert(++p);
// advance p by sizeof(double)
assert(*p == 13.4);
// the double at memory beginning at address p has value 13.4
*(p + 2) = 29.8;
// change sizes[3] from 19.4 to 29.8

Pointers to dynamically allocated memory


Sometimes you don't know how much memory you'll need until your program is running and sees what data
is thrown at it... then you can dynamically allocate memory using malloc . It is common practice to store
the address in a pointer...
int* p = malloc(sizeof(int));
// get some memory somewhere...
*p = 10;
// dereference the pointer to the memory, then write a value in
fn(*p);
// call a function, passing it the value at address p

2 of 5

04/04/2014 03:35 PM

c - What does "dereferencing" a pointer mean? - S...


(*p) += 3;
free(p);

http://stackoverow.com/questions/4955198/what...

// change the value, adding 3 to it


// release the memory back to the heap allocation library

In C++, memory allocation is normally done with the new operator, and deallocation with delete :
int* p = new int(10);
delete p;

// memory for one int with initial value 10

p = new int[10];
delete[] p;

// memory for ten ints with unspecified initial value

p = new int[10]();
delete[] p;

// memory for ten ints that are value initialised (to 0)

Losing and leaking addresses


Often a pointer may be the only indication of where some data or buffer exists in memory. If ongoing use of
that data/buffer is needed, or the ability to call free() or delete() to avoid leaking the memory, then
the programmer must operate on a copy of the pointer...
const char* p = asprintf("name: %s", name);

// common but non-Standard printf-on-heap

// replace non-printable characters with underscores....


for (const char* q = p; *q; ++q)
if (!isprint(*q))
*q = '_';
printf("%s\n", p); // only q was modified
free(p);
...or carefully orchestrate reversal of any changes...
const size_t n = ...;
p += n;
...
p -= n; // restore earlier value...
edited Nov 8 '13 at 8:08

community wiki
14 revs, 2 users 99%
Tony D

Appreciate the way you explained it..... Thanks for sharing pragati May 27 '13 at 9:12
is p[1] and *(p + 1) identical? That is, Does p[1]
Pacerier Sep 22 '13 at 18:20

and *(p + 1) generate the same instructions?

@Pacerier: from 6.5.2.1/2 in the N1570 draft C Standard (first I found online) "The definition of the subscript
operator [] is that E1[E2] is identical to (*((E1)+(E2)))." - I can't imagine any reason why a compiler wouldn't
immediately convert them to identical representations in an early stage of compilation, applying the same
optimisations after that, but I don't see how anyone can definitely prove the code would be identical without
surveying every compiler ever written. Tony D Sep 23 '13 at 6:51
@TonyD, no I'm not talking about compiler implementations, but rather, did the official standard guarantees that
behavior? I mean the latest standards C90, C99, and C11.... Pacerier Sep 24 '13 at 4:13
@Pacerier: the Standards are framed in terms of necessary observable behaviours, but how the compilers
choose to map source code to machine opcodes is not mandated. Tony D Sep 26 '13 at 14:37

Dereferencing a pointer means getting the value that is stored in the memory location pointed by the pointer.
The operator * is used to do this, and is called the dereferencing operator.
int a = 10;
int* ptr = &a;
printf("%d", *ptr); // With *ptr I'm dereferencing the pointer.
// Which means, I am asking the value pointed at by the pointer.

3 of 5

04/04/2014 03:35 PM

c - What does "dereferencing" a pointer mean? - S...

http://stackoverow.com/questions/4955198/what...

// ptr is pointing to the location in memory of the variable a.


// In a's location, we have 10. So, dereferencing gives this value.
// Since we have indirect control over a's location, we can modify its content using
*ptr = 20;

// Now a's content is no longer 10, and has been modified to 20.
edited Jan 29 at 16:15
Migol
2,868 6 24 48

answered Feb 10 '11 at 9:22


Mahesh
20.4k 5 32 60

A pointer doesn't point to a value, it points to an object. Keith Thompson Apr 30 '13 at 5:04
@KeithThompson A pointer does not point to an object, it points to a memory address, where an object
(maybe a primitive) is located. mg30rg Mar 6 at 14:26
@mg30rg: I'm not sure what distinction you're making. A pointer value is an address. An object, by definition, is
a "region of data storage in the execution environment, the contents of which can represent values". And what
do you mean by "primitive"? The C standard doesn't use that term. Keith Thompson Mar 6 at 16:34
@KeithThompson I was barely pointing out, that you did not actually add value to the answer, you were only
nitpicking on terminology (and did that wrong also). The pointer value surely is an address, that's how it
"points" to a memory address. The word "object" in our OOPdriven world can be misleading, because it can be
interpreted as "class instance" (yep, I was not aware that the question is labeled [C] and not [C++]), and I used
the word "primitive" as in the opposite of "copmlex" (data structure like a struct or class). mg30rg Mar 7 at
8:26
@mg30rg: I stand by my original statement: A pointer doesn't point to a value, it points to an object. And the
question was updated to correct that. Terminology is important, and no, I don't believe I got anything wrong.
Incidentally, the C++ standard's definition of the word "object" is very similar to C's, and has nothing to do with
OOP. By "primitive", it sounds like mean what the standard calls "scalar"; yes the object pointed to by a pointer
may or may not be of scalar type, but I'm not sure that adds anything. Keith Thompson Mar 7 at 15:59

Code and explanation from Pointer Basics:


The dereference operation starts at the pointer and follows its arrow over to access its pointee. The goal
may be to look at the pointee state or to change the pointee state. The dereference operation on a
pointer only works if the pointer has a pointee -- the pointee must be allocated and the pointer must be
set to point to it. The most common error in pointer code is forgetting to set up the pointee. The most
common runtime crash because of that error in the code is a failed dereference operation. In Java the
incorrect dereference will be flagged politely by the runtime system. In compiled languages such as C,
C++, and Pascal, the incorrect dereference will sometimes crash, and other times corrupt memory in
some subtle, random way. Pointer bugs in compiled languages can be difficult to track down for this
reason.
void main() {
int*
x; // Allocate the pointer x
x = malloc(sizeof(int));
// Allocate an int pointee,
// and set x to point to it
*x = 42;
// Dereference x to store 42 in its pointee
}
answered Feb 10 '11 at 9:21
ash
5,963 13 56 108
You actually have to allocate memory for where x is supposed to point at. Your example has undefined behavior.
Peyman Feb 10 '11 at 9:23
Your comment postdates my edit ;) ash Feb 10 '11 at 9:25

A pointer is a "reference" to a value.. much like a library call number is a reference to a book.
"Dereferencing" the call number is physically going through and retrieving that book.
int a=4 ;
int *pA = &a ;
printf( "The REFERENCE/call number for the variable `a` is %p\n", pA ) ;
// The * causes pA to DEREFERENCE...

4 of 5

`a` via "callnumber" `pA`.

04/04/2014 03:35 PM

c - What does "dereferencing" a pointer mean? - S...

http://stackoverow.com/questions/4955198/what...

printf( "%d\n", *pA ) ; // prints 4..


If the book isn't there, the librarian starts shouting, shuts the library down, and a couple of people are set to
investigate the cause of a person going to find a book that isn't there.
answered Dec 10 '13 at 18:08
bobobobo
15.7k 14 98 172

In Simple words, dereferencing means accessing the value from certain Memory location against which that
pointer is pointing.
answered Dec 30 '13 at 7:09
Fahad Naeem
30 6

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

5 of 5

04/04/2014 03:35 PM

Das könnte Ihnen auch gefallen