Lab #7, Friday, 2/28

The purpose of this lab is to see some basic pointer manipulation.

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) A palindrome is a word that is the same forwards and backwards. For example, "racecar" is a palindrome. The following program inputs a c-string (array of char) from the user. The string entered must be 14 or fewer characters because the dynamic array created is only big enough to hold 15 characters (one character is needed to store the \0 character to denote the end of the string). You can try entering a larger string - it might still work, or might not, depending upon what memory is overwritten.

Complete the isPalindrome function so it returns true if the c-string passed in as a pointer is a palindrome, and false if it is not.

#include <iostream>
#include <cstring>

bool isPalindrome(char *p, int length);

int main()
   char *cstr = new char[15];
   char c = ' ';

    cout << "Enter a string less than 14 characters." << endl;
    cin >> cstr;
    int len = strlen(cstr);
    cout << "You typed: " << cstr << ". It is " << len << " characters long." << endl;
    cout << "That string " << (isPalindrome(cstr, len) ? "is " : "is not ")
         << "a palindrome." << endl;
    cout << "Enter 'y' to repeat." << endl;
    cin >> c;
   } while (c == 'y');
   delete[] cstr;

bool isPalindrome(char *p, int length)
   // Write code here to make this work.
   // It returns true for now just to make this compile.
   return true;


Show your programs to the lab assistant for credit, or email to by midnight for lab credit.