Given the following C definitions:
#define SYNC_BYTE_1 0x5A
#define SYNC_BYTE_2 0xA5
and pointer declaration:
UINT8 *pCommandData;
pCommandData = GetCommandBufferPointer( LINGO_GENERAL, stringLength + 3 );
What exactly are the following two lines of code doing with the pointer?
*pCommandData++ = SYNC_BYTE_1;
*pCommandData++ = SYNC_BYTE_2;
I specifically don't understand the use of *
and the ++
in this instance. If the pointer's address is being incremented shouldnt the *
be replaced with a &
?
This complexity and the seeming (bold seeming) interchangeability with references ,which is often another caveat of pointers and an error of newcomers, makes understanding pointers hard.
Pointers are arguably the most difficult feature of C to understand. But, they are one of the features which make C an excellent language. In this article, we will go from the very basics of pointers to their usage with arrays, functions, and structure.
First of all, pointers are complicated. Precisely describing their semantics in a way that is consistent with common alias analyses requires adding a notion of “provenance”. In a language such as Java or ML where pointers are opaque types whose representation cannot be observed, this is actually fairly easy to do.
Though powerful tool, a pointer, can be a devil's advocate. If a pointer points to memory that has been freed, or if it is accidentally assigned a nonzero integer or floating point value, it becomes a dangerous way of corrupting memory, because data written through it can end up anywhere.
pCommandData
is a pointer to some piece of memory. The first line
*pCommandData++ = SYNC_BYTE_1;
sets the value at that address to 0x5A
, and then increments the pointer pCommandData
to the next address. The next line
*pCommandData++ = SYNC_BYTE_2;
works similarly: it sets the value that pCommandData
points to, to 0xA5
, and then increments the pointer to the next address.
Perhaps a picture would be useful. Before either line executes, the memory in the neighborhood of wherever pCommandData
points to might look like this:
| |
+--------+
pCommandData -----> | |
+--------+
| |
+--------+
| |
+--------+
| |
After *pCommandData++ = SYNC_BYTE_1;
:
| |
+--------+
pCommandData --+ | 0x5A |
| +--------+
+--> | |
+--------+
| |
+--------+
| |
And after *pCommandData++ = SYNC_BYTE_2;
:
| |
+--------+
pCommandData --+ | 0x5A |
| +--------+
| | 0xA5 |
| +--------+
+--> | |
+--------+
| |
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With