A blog by Devendra Tewari
Some points to remember regarding C pointers
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 return
ed by sizeof
is the same.
A pointer can store the address of another pointer, thus the existence of **
.
If defined within a function its scope is auto
, it is created on the stack and dies when the function return
s.
If passed to another function i.e. callee, the value it stores i.e. the address it points to, is passed to the callee.
To gain access to the value it points to, a pointer has to be dereferenced, this is done by using the *
operator.
A pointer that has a value of 0
is called a null
pointer.
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 return
s, the region of stack used by it is reclaimed, the callee may read values that are, for all effects, junk.
Pointer arithmetic can be used to read array elements, when you add n
to a pointer, you are traversing to the n
th element in the array.
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 {...
ORtypedef struct {...} __attribute__ ((__packed__)) identifier...
OR#pragma pack(1)
void *
is used to store the address of any arbitrary type.