C Pointer - Wikipedia

I thought the LPC_GPIO #define macro uses parameters and the * used is means the parameter.  Actually I was very wrong.  No parameter is used there.  The * is the pointer operator, as described below.


Pointer - Wikipedia

http://en.wikipedia.org/wiki/Pointer_(computer_programming)

C pointers

The basic syntax to define a pointer is:[4]

int *ptr;

This declares ptr as the identifier of an object of the following type:

pointer that points to an object of type int

This is usually stated more succinctly as 'ptr is a pointer to int.'

Because the C language does not specify an implicit initialization for objects of automatic storage duration,[5] care should often be taken to ensure that the address to which ptr points is valid; this is why it is sometimes suggested that a pointer be explicitly initialized to the null pointer value, which is traditionally specified in C with the standardized macro NULL:

int *ptr = NULL;

Dereferencing a null pointer in C produces undefined behavior, which could be catastrophic. However, most implementations simply halt execution of the program in question, usually with a segmentation fault.

However, initializing pointers unnecessarily could hinder program analysis, thereby hiding bugs.

In any case, once a pointer has been declared, the next logical step is for it to point at something:

int a = 5;

int *ptr = NULL;

ptr = &a;

This assigns the value of ptr to be the address of a. For example, if a is stored at memory location of 0x8130 then the value of ptr will be 0x8130 after the assignment. To dereference the pointer, an asterisk is used again:

*ptr = 8;

This means take the contents of ptr (which is 0x8130), "locate" that address in memory and set its value to 8. If a is later accessed again, its new value will be 8.

This example may be more clear if memory is examined directly. Assume that a is located at address 0x8130 in memory and ptr at 0x8134; also assume this is a 32-bit machine such that an int is 32-bits wide. The following is what would be in memory after the following code snippet is executed:

int a = 5;

int *ptr = NULL;

Address Contents

0x8130 0x00000005

0x8134 0x00000000

(The NULL pointer shown here is 0x00000000.) By assigning the address of a to ptr:
 ptr = &a;

yields the following memory values:

Address Contents

0x8130 0x00000005

0x8134 0x00008130

Then by dereferencing ptr by coding:
 *ptr = 8;

the computer will take the contents of ptr (which is 0x8130), 'locate' that address, and assign 8 to that location yielding the following memory:

Address Contents

0x8130 0x00000008

0x8134 0x00008130

Clearly, accessing a will yield the value of 8 because the previous instruction modified the contents of a by way of the pointer ptr.

.END

No comments:

Post a Comment