C / C++ / C#

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

C Tutorial - About Pointers

By David Bolton, About.com

2 of 10

Allocating Memory

As we've seen the Operating System manages applications and their use of memory, so to guarantee that you have safe access to a block of RAM, you have to ask the Operating System for that block. If you don't, then the Operating System will most likely clobber your application by generating an exception if you try to use memory that you haven't properly requested.

To improve reliability Modern processors can protect pages in RAM from being overwritten. Unlike C++ applications which can check for and capture exceptions and continue processing, C applications can't handle exceptions and usually get closed down if one occurs.

If a pointer is used with an existing variable or data then you don't have to allocate memory as it already exists.

Syntax of Pointer Declaration

The * character is used to refer to a pointer.
int variable /* declares an int variable */
int * variable /* declares a pointer to an int variable */
int * variable[5] /* declares an array of 5 pointers, each to an int variable */
void * variable; /* Pointer to anything */
Pointer syntax, especially if arrays are involved can get horribly complex. My advice is to use typedef to simplify the declarations.

Example 1 (Listed on page 4) shows some uses of pointers.Here is what it does.

The variable Fred is a string, or more accurately a pointer to an array of char. Arrays and pointers have a great deal in common. When the compiler builds in a string like this, it adds a hidden '\0' so it will allocate space for 5 characters 't','e','x','t',\0. Fred is just that, a variable and so can be changed. The variable okfred is also a char * but points to nothing as it has not been explicitly initialized.

On the next page Explanation of Example 1 Continued

Explore C / C++ / C#

About.com Special Features

C / C++ / C#

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

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

All rights reserved.