Practice examples: arrays and pointers

Show the output from the following programs:

  1. #include <iostream>
    using namespace std;
    
    // arr is a constant array - contents cannot be changed by f0
    void f0(const int arr[])
    {
       printf("f0\n");
       int a = 9;
       printf("Param addr:  %p Value: %d\n", arr, arr[0]);
       // arr[0]++;  // not allowed to change contents of a const array
       arr = &a;
       printf("After reset: %p Value: %d\n\n", arr, arr[0]);
    }
    
    // arr is a constant ptr - contents cannot be changed by f1
    void f1(const int* arr)
    {
       printf("f0\n");
       int a = 9;
       printf("Param addr:  %p Value: %d\n", arr, arr[0]);
       // arr[0]++;  // not allowed to change contents of a const array
       arr = &a;
       printf("After reset: %p Value: %d\n\n", arr, arr[0]);
    }
    
    // arr is a regular ptr - contents can be changed
    void f2(int *arr)
    {
       printf("f0\n");
       int a = 9;
       printf("Param addr:  %p Value: %d\n", arr, arr[0]);
       arr[0]++;
       arr = &a;
       printf("After reset: %p Value: %d\n\n", arr, arr[0]);
    }
    
    // arr is a regular array - contents can be changed
    void f3(int arr[])
    {
       printf("f0\n");
       int a = 9;
       printf("Param addr:  %p Value: %d\n", arr, arr[0]);
       arr[0]++;
       arr = &a;
       printf("After reset: %p Value: %d\n\n", arr, arr[0]);
    }
    
    // arr is a pointer passed by reference,
    //     both the array contents AND the pointer itself
    //     can be changed by the function
    void f4(int* &arr)
    {
       printf("f0\n");
       int a = 9;
       printf("Param addr:  %p Value: %d\n", arr, arr[0]);
       arr[0]++;
       arr = &a;
       printf("After reset: %p Value: %d\n\n", arr, arr[0]);
    }
    
    int main()
    {
       int array[3] = { 0, 3, 6 };
    
       f0(array);
       f1(array);
       f2(array);
       f3(array);
       // f4(array);  // not allowed, can't pass an array by reference
    
       int *dynamicArray = new int[3];
       if (dynamicArray != NULL) {
          dynamicArray[0] = 0;
          f4(dynamicArray);
          printf("After f4:    %p\n", (dynamicArray));
       }
    }