UC3M

Telematic/Audiovisual Syst./Communication Syst. Engineering

Systems Architecture

September 2017 - January 2018

5.4.  Assigning an address to a pointer

Given a variable var of type t and a variable var_ptr of type pointer to t (t *), it possible to assign

var_ptr = &var

The following example shows the declaration and value assignment of pointers (file pointer_example_1.c):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <stdio.h>
int main() 
{
    int num1, num2;
    int *ptr1, *ptr2;

    ptr1 = &num1;
    ptr2 = &num2;

    num1 = 10;
    num2 = 20;

    ptr1 = ptr2;
    ptr2 = NULL;

    return 0;
}

Lines 4 and 5 define two integers and two pointers to integer respectively. Pointers behave like the rest of variables, they have no initial value. Lines 7 and 8 assign the memory address of the integer variables to the two pointers. The address of a variable exists from the beginning of a program, and therefore, these assignments are correct despite the fact that no value has been yet stored in the variables num1 and num2.

This is a common source of anomalies. The address of a variable may be obtained at any point in the program. A common error is to assign the address of an uninitialized variable to a pointer. The pointer value is correct, but the value it points to is not. In the previous example, before line 10, the two pointers are initialized, but the values they point to, are not.

Line 13 is a pointer assignment. The value of ptr2 is the address of num2 as it was assigned previously. As a result, ptr1 contains now also the address of num2.

Line 14 assigns to pointer ptr2 the constant NULL defined in the stdio.h included in the first line of the program. This constant represents the empty pointer. Its numeric value is zero, and whenever a pointer has this value, it is pointing to nothing.

The following figure shows the evolution for the variables in the program at different execution points. The memory addresses where the variables are stored are arbitrary.

Suggestion

Copy and paste the content of the previous program in a text file in your development environment. Compile to check its syntactic correctness. Make changes in the declarations and assignments, and re-compile to check correctness.

5.4.1.  Self-assessment questions

  1. Three variables are defined, an integer a, a pointer to integer b and a pointer to a pointer to integer c. How can c have the address of the address of the integer a?

    • c = b; b = a;

    • c = b; b = &a;

    • c = &b; b = a;

    • c = &b; b = &a;

  2. Given two variables of any type in a C program, consider the following expression:

    &a == &b;
    • The expression is incorrect.

    • The expression is correct and is always false.

    • The expression is correct and always true.

    • The expression is correct and is true or false depending on the values of a and b.