3.1 Basic pointers

A pointer to an integer is defined as follows:

int *pInt;

We can also defined a named structure, then create a pointer to it:

struct X
{
  int i;
  char name[20];
  float f;
};

struct X *pX;

A pointer does not necessarily point to any location that is accessible. In fact, when a pointer variable is first created, there is no guarantee that it points to any accessible location. A pointer needs to be initialized in order to be useful.

The most basic method to initialize a pointer is to assign the address of a variable (or elements in an array) to it. In our example, we can do the following:

int *pInt;
int i;

pInt = &i;

Or, we can do this to the structure pointer:

struct X *pX;
struct X pool[256];

pX = &pool[5];

We can also ``initialize'' a pointer by passing the address of a variable to a pointer parameter. The following example illustrates this. It also illustrates how a pointer can be dereferenced.

void initInt(int *pInt)
{
  *pInt = 0;
}

int main(void)
{
  int i;

  ...
  initInt(&i);
  ...
}



Copyright © 2006-08-28 by Tak Auyeung