0% found this document useful (0 votes)
6 views7 pages

hw

The document contains a series of programming exercises focused on fixing bugs in C++ code related to pointers, arrays, and string manipulation. Each section presents an original code snippet with identified issues and a corrected version, along with explanations of the problems. Additionally, it includes various functions demonstrating pointer operations and memory management in C++.

Uploaded by

nellebelle
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views7 pages

hw

The document contains a series of programming exercises focused on fixing bugs in C++ code related to pointers, arrays, and string manipulation. Each section presents an original code snippet with identified issues and a corrected version, along with explanations of the problems. Additionally, it includes various functions demonstrating pointer operations and memory management in C++.

Uploaded by

nellebelle
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 7

Genelle Abella

UID 506504346

UCLA COMSCI 31

Professor Smallberg

Project 6 Homework

1a)
int main() {
int arr[3] = { 5, 10, 15 };
int* ptr = arr;

*ptr = 10;
*ptr + 1 = 20; BUG 1! Isn’t properly addressing the second element
ptr += 2;
ptr[0] = 30; /

while (ptr >= arr)


{
ptr--; BUG 2! Eventually goes out of bounds + skips arr[2]
cout << ' ' << *ptr; // print values
}
cout << endl;
}

FIXED VERSION

int main() {
int arr[3] = { 5, 10, 15 };
int* ptr = arr;

*ptr = 10; // OK: sets arr[0] to 10


*(ptr + 1) = 20; // fixed: now sets arr[1] to 20
ptr += 2; // ptr now points at arr[2]
ptr[0] = 30; // OK: sets arr[2] to 30

while (ptr >= arr)


{
cout << ' ' << *ptr; // print first, then...
ptr--; // ...move left
}
cout << endl;
return 0;
}

1b) Original function never change the ptr since the parameters are passed by value

FIX ONLY TO FUNCTION


void findDisorder(int arr[], int n, int*& p) {

for (int k = 1; k < n; k++)


{
if (arr[k] < arr[k-1])
{
p = arr + k;
return;
}
}
p = nullptr;
}

1c) Original main has p uninitialized which writes *resultPtr = into random memory… meaning
undefined behavior

FIX
#include <iostream>
#include <cmath>
using namespace std;

void hypotenuse(double leg1, double leg2, double* resultPtr) {


*resultPtr = sqrt(leg1*leg1 + leg2*leg2);
}
int main() {
double result; // storage for answer
double* p = &result; // p points at result

hypotenuse(1.5, 2.0, p); // OK: *p = √(1.5² + 2.0²)


cout << "The hypotenuse is " << *p << endl;
return 0;
}

1d) Original function compares the pointers instead of the characters they’re pointing at. Also
checks against 0 when it means to check for the null byte ‘\0’.

FIX
// return true if two C-strings are exactly equal
bool match(const char str1[], const char str2[]) {
while (*str1 != '\0' && *str2 != '\0') { // now checks for zero bytes
if (*str1 != *str2) // now compares characters instead of pointers
return false;
++str1;
++str2;
}
return *str1 == *str2; // now compares characters instead of pointers
}

int main() {
char a[20] = "Hong";
char b[20] = "Hung";

if (match(a,b))
cout << "They're the same!\n";
}

1e) The problem with this code is that when computeSquares returns the local array doesn’t exist
anymore (it’s declared in the function). So the pointer that you get back is kinda just hanging
about which is undefined behavior which is why one wouldn’t reliably get back the numbers one
would expect to.

2a) string* fp;

2b) string fish[5];


2c) fp = &fish[4];

2d) *fp = “yellowtail”;

2e)*(fish + 3) = “salmon”;

2f) fp -=3;

2g) fp[1] = “wahoo”;

2h) fp[0] = “tang”;

2i) bool d = (fp == fish);

2j) bool b = (*fp == *(fp + 1));

3a) Same result no incrementing variable ptr, no square brackets

double computeAverage(const double* scores, int nScores) {


double tot = 0;
for (int k = 0; k < nScores; k++)
tot += *(scores + k);
return tot / nScores;
}

3b) Using integer variable k w/o square brackets

const char* findTheChar(const char* str, char chr) {


for (int k = 0; *(str + k) != '\0'; k++)
if (*(str + k) == chr)
return str + k;
return nullptr;
}

3c) No square brackets or integer variables or local variables

const char* findTheChar(const char* str, char chr) {


for (const char* p = str; *p != '\0'; ++p)
if (*p == chr)
return p;
return nullptr;
}

4)

#include <iostream>
using namespace std;

int* minimart(int* a, int* b) // declares function minimart that returns pointers a and b
{
if (*a < *b) // compare the values pointed to by a and b
return a; // if *a is smaller, return pointer a
else
return b; // otherwise return pointer b
}

void swap1(int* a, int *b) // swaps the two pointers (locally)


{
int* temp = a; // temp points to the same location as a
a = b; // local copy of a now points to b’s target
b = temp; // local copy of b now points to temp’s target (original a)

void swap2(int* a, int *b) // correctly swaps the values pointed to by a and b
{
int temp = *a; // temp now equals value at *a
*a = *b; // store the value at *b into *a
*b = temp; // store the saved value into *b
}

int main()
{
int array[6] = { 5, 3, 4, 17, 22, 19 };

int* ptr = minimart(array, &array[2]);


// array to &array[0], &array[2] is pointer to element 2

ptr[1] = 9; // set the element one past so array[3] = 9

ptr += 2; // move ptr two elements forward: now ptr == &array[4]


*ptr = -1; // set the value at current ptr array[4] = -1

*(array + 1) = 79; // array[1] = 79

cout << "diff=" << (&array[5] - ptr) << endl;


// &array[5] is pointer to element 5… gives (5 - 4) == 1

swap1(&array[0], &array[1]);
// attempts to swap pointers to elements 0 and 1, but does nothing to the array

swap2(array, &array[2]);
// for real this time swaps the values at array[0] and array[2]

for (int i = 0; i < 6; i++)


cout << array[i] << endl;
// prints the element of array[0] through array[5] w/ nelines

return 0;
}

PRINTS:

diff=1
4
79
5
9
-1
19

5) deleteG function that accepts character pointer as parameter, returns nothin, remove all cases
of G/g resulting in valid c string, only 1 local variable no square brakets no cstring func.

void deleteG(char* str) {


char* p = str; // extra pointer to lok through original string
while (*p) {
if (*p != 'g' && *p != 'G') {
*str++ = *p; // bring non-‘g’ characters forward
}
++p; // moves scan pointer forward
}
*str = '\0'; // kills resulting c- string
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy