CP1300 C++ Pointers

Last modified Tuesday, 17-Oct-2000 05:01:02 UTC.

Self assessments


Tutorial Questions


Exam style questions

  1. Write a declaration for a variable that points at a char.
  2. What is the output from this code?
    int anInt;
    int *intP1;
    int *intP2;
    
    intP1 = &anInt;
    *intP1 = 27;
    anInt = 27;
    intP2 = new int;
    *intP2 = 16;
    intP1 = intP2;
    *intP1 = 27;
    
    cout << anInt << " " << *intP1 << " " << *intP2 << endl;
         
  3. Write a code segment that declares an array of 10 pointers to int, initializes all of them to point at the int variable anInt, and finally prints out the contents of anInt using the 5th array element.
  4. What is the output from the following code?
    char name[12];
    char *offset;
    
    strcpy(name,"Sutcliffe");
    offset = &name[4];
    cout << offset << endl;
         
  5. Write a code segment that declares a pointer to a float, and then makes the pointer be the "name" of a newly created array of 10 floats.
  6. If FredsClass is a class that has only a default constructor, write a code segment that declares a pointer to a FredsClass object, and creates a new object pointed to by the variable.
  7. What is the output from the following program?
    //-----------------------------------------------------------------------------
    #include 
    
    typedef int *intPointer;
    
    void makeANewInt(intPointer intP1,intPointer &intP2);
    //-----------------------------------------------------------------------------
    int main(void) {
    
    int anInt;
    intPointer pointAtInt;
    
    anInt = 27;
    pointAtInt = &anInt;
    makeANewInt(pointAtInt,pointAtInt);
    cout << *pointAtInt << endl;
    
    return(0);
    }
    //-----------------------------------------------------------------------------
    void makeANewInt(intPointer intP1,intPointer &intP2) {
    
    intP2 = new int;
    *intP2 = *intP1 *2;
    
    }
    //-----------------------------------------------------------------------------