C / C++ / C#

  1. Home
  2. Computing & Technology
  3. C / C++ / C#

C++ Tutorial - About Pointers

By David Bolton, About.com

4 of 10

Explanation of Example 1 Continued

Okfred requests a block of memory big enough to hold the string "David" plus 1 by calling the new operator. This memory is allocated in the heap. The function strlen() (from <string.h>) returns the length of "david" which is 5. It does not include the terminating '\0' so the + 1 handles that. The variable Fred is now set to point to this 6 byte allocated block. The string "david" with a terminating '\0' is written to this block, character by character. This is a long winded way to assign a string as there are functions in the <string.h> library that do this but it gives a basic idea. The second character of this block is subsequently overwritten using the address *(Fred+1).

Note that when you increment a pointer or offset (like I did with *(Fred+1)), the pointer address is changed by the size of whatever it points to. So in OkFred++, it increments by 1- the size of an 8 bit character. If it were an int * then the pointer would alter by the size of int which is normally 4 bytes. You can see this with the array b that holds two ints. The variable int *Ptrb points to b (which is the same address as b[0]). Incrementing Ptrb now points it to b[1].

I've used the address operator & to give the address of variables. This is not needed for an array name. The addresses b and &b are the same value. This isn't true for individual array elements such as b[0] and &b[0] though. If you print b[1] you get the value stored there not the address!

On the next page : Example 1 listing

Explore C / C++ / C#

About.com Special Features

C / C++ / C#

  1. Home
  2. Computing & Technology
  3. C / C++ / C#
  4. C++
  5. Learn C++ Programming
  6. Explanation of Example 1 Continued

©2009 About.com, a part of The New York Times Company.

All rights reserved.