Pointers


  1. How do you access the memory address of a variable?

  2. How do you access the contents of a memory location whose address is stored in a pointer?

  3. Given the following declarations:
    
    int	*p, *q;
    int n;
    
    Which of the following is valid?
    1. p+q
    2. p+n
    3. p-q
    4. q-n
    5. n-p

  4. Given the following declaration
    
    float	a[10];
    float	*a_ptr;
    
    What do the following statements do? Assume that they are executed in the order given.
    1. a_ptr = a;
    2. a_ptr ++;
      *a_ptr = 3.5;
      
    3. a_ptr = a_ptr + 5;
      *a_ptr = a[1];
      

  5. When referring to command line arguments what is the argument count?

    How many arguments are in the following command line?

    
    prog -x -a file1 13
    
    What is stored in argv[2]?


Answers











































  1. The memory address of a variable is accessed using the address operator &. Given the variable x it's address is &

  2. The contents of a memory location pointed to by a pointer are accessed using the de-referencing operator (*). The contents of the memory location pointed to by p are accessed by *p.

    1. p+q - This is invalid. We cannot add two pointers.
    2. p+n - This is valid. It increments the memory address p points to by n.
    3. p-q - This is valid. The subtraction of the two pointers gives the number of integer variables stored between the two locations
    4. q-n - This is valid. It decrements the memory address q points to by n
    5. n-q - This is invalid. We cannot subtract a pointer from an integer.

    1. This makes the pointer a_ptr point to the beginning of the array (element number 0 of array a)
    2. This increments the pointer so it now points to a[1]. The contents of a[1] then becomes 3.5.
    3. It increments the pointer by 5 places - so it now points to a[6]. It then copies the value of a[1] (3.5) to a[6].

  3. The argument count is the number of arguments specified on the command line to run the program.

    There are 5 arguments.

    argv[2] contains -a


Back to Questions Back to Main Page for Lecture 7