The &
operand followed by a variable name
returns its memory address. The data type of the result is “pointer
to” followed by the type of the used variable. The rule to obtain the
syntax and meaning of these data types is:
For each data type
T
there exists a data type called “Pointer to T” defined as “T *
”.
In the following table the consequences of applying this rule to the basic C data types are shown together with some examples of variable declarations.
Type T | Size (bytes) [a] | Pointer to T | Size (bytes) | Example of use |
---|---|---|---|---|
int | 4 | int * | 4 | int *a, *b, *c; |
unsigned int | 4 | unsigned int * | 4 | unsigned int *d, *e, *f; |
short int | 2 | short int * | 4 | short int *g, *h, *i; |
unsigned short int | 2 | unsigned short int * | 4 | unsigned short int *j, *k, *l; |
long int | 4 | long int * | 4 | long int *m, *n, *o; |
unsigned long int | 4 | unsigned long int * | 4 | unsigned long int *p, *q, *r; |
char | 1 | char * | 4 | char *s, *t; |
unsigned char | 1 | unsigned char * | 4 | unsigned char *u, *v; |
float | 4 | float * | 4 | float *w, *x; |
double | 8 | double * | 4 | double *y, *z; |
long double | 8 | long double * | 4 | long double *a1, *a2; |
[a] Reference balues, they change depending on the platform |
Additionally to the pointers to the created data types, C
allows to declare a generic pointer of type void *
. A variable
of this type stores a pointer to any data. It is recommended to restrict
the use of this type only when there is no other option.
The size of pointers is always the same regardless of the data they point because all of them store a memory address. In the case of data structures, the rule applies exactly the same. The following example shows how a structure is defined and a variable and a pointer to that structure are declared:
Variable contact1
is a structured type and
occupies 44 bytes (20 + 20 + 4), while contactPointer
is of
type pointer and only occupies 4 bytes.