Lab #6, Friday, 10/5

The purpose of this lab is to see some basic pointer manipulation and command line arguments, which uses an array of pointers.

1)  In the C programming language there is no pass by reference syntax to pass a variable by reference to a function. Instead a variable is passed by pointer (just to be confusing, sometimes passing by pointer is called pass by reference). This lab asks you to do the same thing as C, even though normally you would just use C++'s reference parameter syntax. Here is the header for a function that takes as input a pointer to an integer:

       void absoluteValue(int *ptrNum)
Complete the function so it changes the integer referenced by ptrNum to hold the absolute value of the original value. Write a main function where an integer variable is defined, give it an initial value, call absoluteValue sending in the address of the variable, and output the variable. Test it twice, once with a positive and again with a negative number.

 

2) In C++ we can specify the following for main:

       int main(int argc, char *argv[])            

These parameters are used when the program is invoked from the command line. The parameter argc tells us how many arguments are used in invoking the program. This includes the program name itself. For example if we run the program using:

       ./a.out            
Then argc would equal 1 because the only parameter is the program name of ./a.out.  If we run the program using:
       ./a.out 45 10            
Then argc would equal 3 because there are three parameters (./a.out, 45, and 10). The argv parameter is an array of char pointers (i.e. cstrings). argv[0] points to a cstring that represents the first argument (e.g. ./a.out), argv[1] points to a cstring that represents the second argument (e.g. 45) and so on.  You may want to run this on the unix machine or some other place where it is easy to supply command line arguments. You can do the same thing in Windows but will need to open up a command shell and navigate to the folder containing your compiled executable (there is also a way to specify command line arguments in Visual Studio's project settings). Here is an example program that outputs all of the command line arguments:
#include <iostream>
#include <cstdlib>

using namespace std;

int main(int argc, char *argv[])
{
  for (int i = 0; i < argc; i++)
  {
    cout << argv[i] << endl;
  }
  return 0;
}

Modify this program so that it outputs the smallest of all the numbers sent in on the command line.  It should take an arbitrary number of values.  You can assume they are all integers.  For example, here is a sample run:

[kjmock@transformer test]$ ./a.out 30 10 5 42
5            

To convert a c-string into an integer, use the atoi function.  For example, atoi("20") returns back the integer 20.

 

Show your programs to the lab TA for credit, or email to kjmock@alaska.edu by midnight for lab credit.