C Programming Data Pointers
Variable Address vs Variable Value
In some situations, we will want to work with a variable's address in memory, rather than the value it contains:
A pointer is essentially a variable that holds the address of another variable or function. Pointers may be used to perform what is known in the assembly language world as indirect addressing. When you use pointers, you are able to access the variable that they point to and you are able to change the pointer so that it points to a different variable. This simple mechanism has hundreds of uses and is one of the most powerful features of the C programming language.
A pointer allows us to indirectly access a variable.
Pointers make it possible to write a very short loop that performs the same task on a range of memory locations/variables.
Example
Data Buffer
2 char *bufPtr = &buffer;
3
4 while ((DataAvailable) && (ReceivedCharacter != '\0'))
5 {
6 //Read byte from UART and write it to RAM buffer
7 ReadUART(bufPtr);
8 //Point to next available byte in RAM buffer
9 bufPtr++;
10 }
RAM buffer allocated over a range of addresses (perhaps an array).
Pseudo-code:
1. Point arrow to the first address of the buffer.
2. Write data from the Universal Synchronous Receiver Transmitter (UART) to the location pointed to by the arrow.
3. Move the arrow to point to the next address in the buffer.
4. Repeat until data from the UART is 0 or buffer is full (arrow points to last address of buffer).
Pointers may be used in many ways. Some of the more common include being used in conjunction with dynamic memory allocation. A pointer may point to a location in the heap where a variable is created at runtime since the variable doesn't have a name in the same way as the variables we explicitly declare before compilation.
More frequently, you will see pointers used as a mechanism to pass multiple parameters to or from a function or as a way to pass a value BY REFERENCE to a function. Since C ordinarily passes variables to functions BY VALUE, the original variable is never changed. In some cases, we want to modify the original variable as a part of the function's operation. Therefore, we can pass a pointer to the function and it will then be able to modify the original variable (much more on this later). Pointers also provide an alternate means of accessing arrays which can be more efficient, especially when dealing with strings.