UC3M

Telematic/Audiovisual Syst./Communication Syst. Engineering

Systems Architecture

September 2017 - January 2018

5.3.  The pointer to data type

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
int4int *4int *a, *b, *c;
unsigned int4unsigned int *4unsigned int *d, *e, *f;
short int2short int *4short int *g, *h, *i;
unsigned short int2unsigned short int *4unsigned short int *j, *k, *l;
long int4long int *4long int *m, *n, *o;
unsigned long int4unsigned long int *4unsigned long int *p, *q, *r;
char1char *4char *s, *t;
unsigned char1unsigned char *4unsigned char *u, *v;
float4float *4float *w, *x;
double8double *4double *y, *z;
long double8long double *4long 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.

5.3.1.  Self-assessment questions

  1. An array with two 4-byte integers is defined as int array[2] and is stored starting at position 100 in memory. The following code is executed:

    array[0] = 20;
    array[1] = 30;

    What is the value of the integer stored in position 104 of memory?

    • 2

    • 20

    • 30

    • 104

    And in which memory address is stored the first element of the array?

    • 100

    • 101

    • 102

    • 103

  2. In a program these two variables are defined:

    int i = 10;
    int *i_ptr;

    If variable i is stored in memory position 100, what value contains the i_ptr variable?

    • Value 100 which is the address of variable i.

    • Value 104 because it is the position that follows those occupied by i.

    • No value because it has not been initialized.

    • Its own memory address.

  3. If a variable has to store the address of the address of a character, what must be the type of its definition?

    • char *

    • ** char

    • char **

    • string **