Points to remember regarding C pointers


Some points to remember regarding C pointers:

  1. A pointer is like any value type, but the value it stores is an address, that is why pointers to any type have the same size i.e. value returned sizeof is the same.
  2. A pointer can store the address of another pointer, thus the existence of **.
  3. If defined within a function its scope is auto, it is created on the stack and dies when the function returns.
  4. If passed to another function i.e. callee, the value it stores i.e. the address it points to, is passed to the callee.
  5. To gain access to the value it points to, a pointer has to be dereferenced, this is done by using the * operator.
  6. A pointer that has a value of 0 is called a null pointer.
  7. To get the address of any identifier, the & operator can be used. Don’t pass pointer to a variable of scope auto to a callee that may retain it for use at some future point in time. Once the caller returns, the region of stack used by it is reclaimed, the callee may read values that are, for all effects, junk.
  8. Pointer arithmetic can be used to read array elements, when you add n to a pointer, you are traversing to the nth element in the array.
  9. A pointer may be cast to a struct pointer, and the attributes of the struct read or written to. Beware of byte ordering i.e. endianness, and struct memory alignment, when you memcpy data between devices with different processor architectures. Usage of appropriate compiler directive, packed attribute of GCC for instance, is recommended to prevent padding from causing issues e.g.
    • struct __attribute__ ((__packed__)) identifier {... OR
    • typedef struct {...} __attribute__ ((__packed__)) identifier... OR
    • #pragma pack(1)
  10.  A void * is used to store the address of any arbitrary type.

One thought on “Points to remember regarding C pointers

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s