Lab #6, Wednesday, 10/4

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 addOne(int *ptrNum)
Complete the function so it adds one to the integer referenced by ptrNum. Write a main function where an integer variable is defined, give it an initial value, call addOne, and output the variable. It should be incremented by one.

 

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.  Here is an example program that outputs all of the command line arguments.  You will probably want to run this on the unix machine or some other place where it is easy to supply 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 sums all of 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
45            

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

 

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