hw
hw
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; /
FIXED VERSION
int main() {
int arr[3] = { 5, 10, 15 };
int* ptr = arr;
1b) Original function never change the ptr since the parameters are passed by value
1c) Original main has p uninitialized which writes *resultPtr = into random memory… meaning
undefined behavior
FIX
#include <iostream>
#include <cmath>
using namespace std;
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.
2e)*(fish + 3) = “salmon”;
2f) fp -=3;
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 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 };
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]
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.