You are on page 1of 17

CS 300

Problem Set 1
(Not to be graded)

1) What is a pointer in C++? What are the usages of pointers, which part of the memory
are they stored in? What are some special commands when dealing with pointers?

2) What is a dangling pointer? What causes this pointer type?

3) What is the difference between an uninitialized pointer and a null pointer?

4) What is a segmentation fault?

5) The expressions *ptr++ and ++*ptr are the same (True/False)

6) The following declarations are the same (True/False):

char **apple
char *apple[]
char apple[][]

7) The following statements are the same (True/False):

char *p=0;
char *t=NULL;

8) The dynamically allocated space within a function call gets automatically deallocated
when the function returns (True/False)
9) What is the issue with the following code?

char *foo()
{
char *str = “hello world”;
return str;
}
char *mystring;
mystring = foo();
printf(“mystring = %s\n”, mystring);

10) Consider the following function that shall return a pointer to a Date object
representing the date of tomorrow.

Please refer to the attached date.h and date.cpp files for further information
about the Date class.

Date* tomorrow() {
Date today;
today++;
return &today;
}

Isolate and fix the defect present in the code.

11) Describe what happens when the new operator is called and there is insufficient
amount of memory available for the allocation.

12) A LinkedList class is given in the appendix. Add a new method to this class that
counts the number of elements stored in the list. Provide both a recursive and a non-
recursive implementation.
13) What does the following function do?

struct Node{
int data;
Node *next;
};

Node* foo(Node *head){


// Assume that head points to the head of a linked list,
// and no dummy header node is used in the implementation of
// the list.

Node *next = NULL;


Node *previous = NULL;
Node *current = head;

while (current != NULL){


next = current->next;
current->next = previous;
previous = current;
current = next;
}

return previous;
}

14) Isolate and fix the defect(s) present in the following code segment.

void circle_area(int r){


static const double pi = 3.14;
double *area;

*area = pi*r*r;

cout << "Area of a circle with r=" << r << " is " << *area << endl;
}

int main(){
for(int i=1; i<10000; i++){
circle_area(i);
}
}
15) Isolate the defect in the following code segment.

void foo(Date *p){


cout << p->ToString() << endl;
delete p;
}

Date *t = new Date();


Date *d = t;
foo(t);
cout << d->ToString() << endl;

16) Given

#define SIZE 100

int A[SIZE];
Date B[SIZE];

int idx;
for(idx = 0; idx < SIZE; idx++){ A[idx] = idx + 1; }
for(idx = 0; idx < SIZE; idx++){ B[idx] += idx; }

int *i = A + 55;
Date *d = B + 28;

describe the effect of every statement below. Assume that the statements are executed
in the order given:

a) i++;
b) *i++ = 0;
c) (*i)++ = -1;
d) d--;
e) *(d-10) += 1;
f) cout << (*d).ToString() << endl;
g) *(d - 30) += 1;
17) Isolate and fix the defect present in the following code segment.

int row_count = 10;


int column_count = 5;
int **dynamicArray;

dynamicArray = new int *[row_count];


for( int i = 0; i < row_count; i++ ){
dynamicArray[i] = new int[column_count];
}

delete [] dynamicArray;

for( int i = 0; i < row_count; i++ ) {


delete [] dynamicArray[i];
}

18) The function insertFront shall insert a new node containing the element data at
the head of a linked list and return a pointer to the new head. Isolate and fix the
defect present in the implementation of this function without modifying the Node
class.

class Node{
public:

Node(int d, Node *n)


:data(d),next(n){ }

private:
int data;
Node *next;
};

Node* insertFront(Node *head, int data){


// Assume that head points to the head of a linked list,
// and no dummy header node is used in the implementation of
// the list.

Node *newNode = new Node(data, NULL);


newNode->next = head;

return newNode;
}
Appendix
date.cpp
#include "date.h"
#include <time.h>
#include <stdio.h> // for sprintf

/********************************************************************
This code is freely distributable and modifiable providing you
leave this notice in it.
Copyright @ Owen Astrachan
********************************************************************/

static int DaysInMonth(int,int); // # of days in month in year


static bool IsLeap(int year); // is year a leap year

static string dayNames [] = {"Sunday", "Monday", "Tuesday","Wednesday",


"Thursday","Friday", "Saturday"};

static string monthNames [] = {"January","February","March","April",


"May","June","July","August",
"September","October","November","December"};

Date::Date()
// postcondition: date initialized to default date (today)
{
static struct tm timeHolder;
static struct tm *date = &timeHolder;
time_t tloc;

time(&tloc);

date = localtime(&tloc);

myMonth = date->tm_mon+1;
myDay = date->tm_mday;
myYear = date->tm_year+1900; // struct tm based on 1900
}

Date::Date(int m, int d, int y)


// postcondition: date properly initialized for date m/d/y (american style)
// exception: if m isn't between 1 and 12, converted to 1
// if d out of range for month, converted to 1
{
CheckDate(m,d,y);
}

Date::Date(long days)
// postcondition: date initialized corresponding to absolute days
// after 1 A.D.
{
// this code is taken from "Calendrical Calculations, II"
// Reingold and Dershowitz and Clamen
// Software Practice and Experience, V. 23(4) 383-404 (april 1993)
long prior = days - 1; // prior days
long years400 = prior / 146097L; // # of 400 year cycles
long days400 = prior % 146097L; // days NOT in years400

long years100 = days400 / 36524L; // # 100 yr. cycles not checked


long days100 = days400 % 36524L; // days NOT already included

long years4 = days100 / 1461L; // # 4 yr cycles not checked


long days4 = days100 % 1461L; // days NOT already included

long year1 = days4 / 365L; // # years not already checked


long day1 = days4 % 365L; // days NOT already included

// use "magic formula" from SP&E article


long finalDay;
long finalYear = 400*years400 + 100*years100 + 4*years4 + year1;

if (years100 == 4 || year1 == 4){ // December 31 of leap year


finalDay = 366;
}
else{
finalDay = day1 + 1;
finalYear += 1;
}

// now have year and day #, find month and day in month
myMonth = 1;
while (myMonth <= 12 && 0 < finalDay){
finalDay -= DaysInMonth(myMonth, int(finalYear));
myMonth += 1;
}
myMonth -= 1; // went one to far
finalDay += DaysInMonth(myMonth, int(finalYear));

myDay = int(finalDay);
myYear = int(finalYear);
}

int Date::Month() const


// postcondition: returns month of Date
{
return myMonth;
}

int Date::Day() const


// postcondition: returns day of Date
{
return myDay;
}

int Date::Year() const


// postcondition: returns year of Date
{
return myYear;
}

string Date::ToString() const


// postcondition: returns string (ascii) for date: day, month, year
{
const int BUFSIZE = 50;
char buf[BUFSIZE];
sprintf(buf," %d %d",myDay, myYear);

return MonthName() + buf;


}

static bool IsLeap(int year)


// postcondition: returns 1 if year is a leap year, else returns 0
{
if (year % 400 == 0){
return true;
}
else if (year % 100 == 0){
return false;
}
else if (year % 4 == 0){
return true;
}

return false;
}

static int DaysInMonth(int month,int year)


// postcondition: returns # of days in month in year
{
int days = 30;

// 30 days hath september, april, june, and november


// other months have 31 as below (except February)

if (month == 1 || month == 3 || month == 5 || month == 7 ||


month == 8 || month == 10 || month == 12){
days = 31;
}
else if (month == 2){ // treat February differently
days = 28;
if (IsLeap(year)){ // add 1 for leap years
days += 1;
}
}
return days;
}

int Date::DaysIn() const


{
return DaysInMonth(myMonth,myYear);
}

long Date::Absolute() const


// postcondition: returns absolute # days corresponding to Date
// assuming January 1, 1 B.C is day 1
{
int m = 1; // start in January;
int daysBefore = 0; // count # days before month

while (m < myMonth){ // tally # of days in preceding months


daysBefore += DaysInMonth(m,myYear);
m += 1;
}

// days before this year


long dayYears = 365 * ((long)(myYear) - 1);

// add 1 extra day for each leap year

int leapYears = (myYear - 1) / 4; // initial # of leap years

leapYears -= (myYear - 1) / 100; // subtract years divisible by 100


leapYears += (myYear - 1) / 400; // add back years divisibly by 400

return myDay + daysBefore + dayYears + leapYears;


}

string Date::DayName() const


{
return dayNames[int(Absolute() % 7)];
}

string Date::MonthName() const


{
return monthNames[myMonth-1];
}

ostream & operator << (ostream & os, const Date & d)
{
os << d.ToString();
return os;
}

Date& Date::operator +=(long dx)


{
*this = Date(Absolute()+dx);
return *this;
}

Date& Date::operator -=(long dx)


{
*this = Date(Absolute()-dx);
return *this;
}

Date Date::operator ++(int)


{
Date hold = *this;
*this += 1;
return hold;
}

Date Date::operator --(int)


{
Date hold = *this;
*this -= 1;
return hold;
}

Date operator + (const Date & d, long dx)


{
return Date(d) += dx;
}

Date operator + (long dx, const Date & d)


{
return d+dx;
}

Date operator - (const Date & d, long dx)


{
return Date(d) -= dx;
}

long operator - (const Date & lhs, const Date & rhs)
{
return lhs.Absolute() - rhs.Absolute();
}

void Date::CheckDate(int m, int d, int y)


{
if (m < 1 || 12 < m) // month out of range?
{ m = 1;
}
myMonth = m;

if (d < 1 || DaysInMonth(m,y) < d) // day out of range?


{ d = 1;
}
myDay = d;
myYear = y;
}

bool Date::Equal(const Date & rhs) const


{
return Absolute() == rhs.Absolute();
}

bool Date::Less(const Date & rhs) const


{
return Absolute() < rhs.Absolute();
}
bool operator == (const Date & lhs, const Date & rhs)
{
return lhs.Equal(rhs);
}

bool operator != (const Date & lhs, const Date & rhs)
{
return ! (lhs == rhs);
}

bool operator < (const Date & lhs, const Date & rhs)
{
return lhs.Less(rhs);
}

bool operator > (const Date & lhs, const Date & rhs)
{
return rhs < lhs;
}

bool operator <= (const Date & lhs, const Date & rhs)
{
return lhs == rhs || lhs < rhs;
}

bool operator >= (const Date & lhs, const Date & rhs)
{
return rhs <= lhs;
}
date.h
#ifndef _DATE_H
#define _DATE_H

/********************************************************************
This code is freely distributable and modifiable providing you
leave this notice in it.
Copyright @ Owen Astrachan
********************************************************************/
#include <iostream>
#include <string>
using namespace std;

// a class for manipulating dates


//
// Date class represents a date in the Gregorian calendar
// works only for dates after October, 1752
//
// attempts to construct invalid dates, e.g., 15 month,
// or 38th day result in month == 1, day == 1. years aren't checked
// for validity
//
// Date() --- construct default date (today)
// Date(long days) --- construct date given absolute # of days from
// 1 A.D., e.g., 710,347 = November 12, 1945
//
// Date(int m,int d,int y) --- constructor requires three parameters:
// month, day, year, e.g.,
// Date d(4,8,1956); initializes d to represent
// the date April 8, 1956. Full year is required
//
//
// int Month() --- return, respectively, month, day, and year
// int Day() corresponding to date with 1 = january,
// int Year() 2 = february, ... 12 = december
//
//
// string DayName() --- return string corresponding to day of week
// either "Monday", "Tuesday", ... "Sunday"
// string MonthName() --- return string corresponding to month
// either "January", "February",..."December"
//
// int DaysIn() --- return number of days in month
//
//
// long Absolute() --- returns absolute # of date assuming
// that Jan 1, 1 AD is day 1. Has property
// that Absolute() % 7 = k, where k = 0 is sunday
// k = 1 is monday, ... k = 6 is saturday
//
// string ToString() -- returns string version of date, e.g.,
// -- d.SetDate(11,23,1963); then d.ToString()
// returns string "November 23 1963"
// *************************************************
// arithmetic operators for dates
// *************************************************
//
// dates support some addition and subtraction operations
//
// Date d(1,1,1960); // 1960 is a leap year
// d++; // d represents January 2, 1960
// d--; // d is back to January 1, 1960
// d += 31; // d is February 1, 1960
// d -= 32; // d is December 31, 1959
// Date d2 = d + 1; // d2 is January 1, 1960
// Date d3 = 365 + d2; // d3 is December 31, 1961
// Date d4 = d - 1; // d4 is December 30, 1959
//
// *************************************************
class Date
{
public:
// constructors
Date(); // construct date with default value
Date(long days); // construct date from absolute #
Date(int m,int d,int y); // construct date with specified values

// accessor functions

int Month() const; // return month corresponding to date


int Day() const; // return day corresponding to date
int Year() const; // return year corresponding to date
int DaysIn() const; // return # of days in month
string DayName() const; // "monday", "tuesday", ... or "sunday"
string MonthName() const; // "january","february",... or "december"
long Absolute() const; // number of days since 1 A.D. for date
string ToString() const; // returns string for date in ascii

bool Equal(const Date & rhs) const; // for implementing <, >, etc
bool Less(const Date & rhs) const;

// mutator functions

Date operator ++(int); // add one day, postfix operator


Date operator --(int); // subtract one day, postfix operator
Date& operator +=(long dx); // add dx, e.g., jan 1 + 31 = feb 1
Date& operator -=(long dx); // subtract dx, e.g., jan 1 - 1 = dec 31

private:

int myDay; // day of week, 0-6


int myMonth; // month, 0-11
int myYear; // year in four digits, e.g., 1899

void CheckDate(int m, int d, int y); // make sure that date is valid
};

Date operator + (const Date & d, long dx); // add dx to date d


Date operator + (long dx, const Date & d); // add dx to date d
Date operator - (const Date & d, long dx); // subtract dx from date d
long operator - (const Date & lhs, const Date & rhs);

ostream & operator << (ostream & os, const Date & d);
bool operator == (const Date & lhs, const Date & rhs);
bool operator != (const Date & lhs, const Date & rhs);
bool operator < (const Date & lhs, const Date & rhs);
bool operator > (const Date & lhs, const Date & rhs);
bool operator <= (const Date & lhs, const Date & rhs);
bool operator >= (const Date & lhs, const Date & rhs);

#endif
LinkedList.h
#ifndef _LINKEDLIST_H
#define _LINKEDLIST_H

#include <iostream>
#include <string>
using namespace std;

//class for manipluating linked lists

#define NOT_EXISTS -6113

struct Node{

int data;
Node *next;

Node(){ data = NOT_EXISTS; next = NULL; }


Node(int _data, Node *_next){ data = _data; next = _next; }
};

class LinkedList{

public:
LinkedList();
~LinkedList();
Node * AddNode(int _data);
void DeleteNode(int _data);
void PrintList();
void DeleteList();

private:
Node * head;
};

#endif _LINKEDLIST_H
LinkedList.cpp
#include "linkedlist.h"

LinkedList::LinkedList(){
head = new Node();
}

LinkedList::~LinkedList(){
DeleteList();
}

void LinkedList::DeleteList(){
Node *temp = new Node();
Node *start = head;
while (start != NULL) {
if(start->next != NULL) //if we are not at the last node
temp = start->next;
else
temp = NULL;
delete start;
start = temp;
}
head = NULL;
}

Node * LinkedList::AddNode(int _data){

//First find the last node


Node *p = head;
while(p->next)
p = p->next;

//Append the new node


Node *temp = new Node();
temp->data = _data;
p->next = temp;

return temp;
}

void LinkedList::PrintList(){

int i=0;
Node *p = head;
if( p == NULL ){
cout << "There are no elements in the list!!" << endl;
}
else {
while(p != NULL){
if(p->data != NOT_EXISTS)
cout << "Node " << i << " :" << p->data << endl;
p = p->next;
i++;
}
}
}

//If there are more than one node with the same
//data content, then the last one is deleted
void LinkedList::DeleteNode(int _data){

Node *prev = new Node();


Node *p = head;
while(p != NULL){
if(p->data == _data) { //The node to be deleted is found
prev->next = prev->next->next;
p->next = NULL;
delete p;
p = prev;
}
prev = p;
p = p->next;
}
}

You might also like