0% found this document useful (0 votes)
48 views10 pages

Sheet1 - Solution - Pointers, Functions and Arrays

Pointer arithmetic allows pointers to be treated as arrays and incremented or decremented to access different memory locations. The key points are: 1) B points to the second element of array A. B[0] is the same as A[2]. 2) C points 6 elements past A. C[0] is the same as A[6]. 3) Subtracting pointers gives the number of elements between them, not bytes. C - B is 4 elements.

Uploaded by

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

Sheet1 - Solution - Pointers, Functions and Arrays

Pointer arithmetic allows pointers to be treated as arrays and incremented or decremented to access different memory locations. The key points are: 1) B points to the second element of array A. B[0] is the same as A[2]. 2) C points 6 elements past A. C[0] is the same as A[6]. 3) Subtracting pointers gives the number of elements between them, not bytes. C - B is 4 elements.

Uploaded by

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

Programming Techniques Sheet #1 - Solution

Cairo University
Faculty of Engineering
Computer Engineering Department
Programming Techniques
Sheet #1 - Solution Commented [E1]:
[Sheet Topics]:

Pointers, Functions and Arrays -Pointers and dynamic alloc. (Q1)


-Pointer Arithmetic (Q2, Q3.a)
-Alias Variable (Q3. b)
-Const. Pointer and Pointer to Const. (Q4. a, c)
1. For each of the following programs, state whether it is valid or has problems. If a program is -Returning an address of an automatic var. (Q4. b)
valid, write the expected output. If not, state the problem and how to solve it. -Functions (with pointers, arrays and different types of
passing parameters) (from Q5 to Q11)
-Character Arrays (Q12)
A. int x = 5; B. int x = 5; C. for(int i=0; i<3; i++)
if ( x > 0 ) if ( x > 0 ) {
{ { cout << i;
x = 10; int x = 10; }
int y = 1; cout << x; cout << i;
cout << x << y; }
} cout << x;
cout << x << y;
D. int x = 6; E. F.
if (x > 0) int x = 5;//address 0x50 int x = 5;//address 0x50
{ int y = 10;//address 0x54 int y = 10;//address 0x54
int *p = &x; int * ptr1 = &x; int * ptr1 = &x;
*p = 99; int * ptr2 = ptr1; int * ptr2 = &y;
} cout << ptr1 << ptr2; *ptr1 = *ptr2;
cout << x; *ptr2 = 99; cout << x << y << *ptr1;
cout << *p; cout<<x <<y <<*ptr1; *ptr2 = 99;
ptr2 = &y; cout << *ptr1;
cout << ptr1 << ptr2;
*ptr1 = 88;
cout<<x <<y <<*ptr2;
G. int * ptr; H. int x; I. int x = 5;
*ptr = 5; int* ptr = &x; int *ptr;
cout << *ptr; int * ptr2 = &x;
*ptr = &x;
J. int x = 5; K. int * q, x; L. int * q;
int * ptr = &x; if ( true ) if ( true )
*ptr = *x; { {
int * p; int * p;
p = &x; p = new int;
*p = 10; *p = 10;
cout << x; q = p;
q = p; }
} *q = 5;
*q = 5; delete q;
cout << x;
M. N. int * p = new int; O. int * p = new int;
int * p = new int; *p = 10; int * q = p;
*p = 10; delete p; delete p;
delete p; p = new int [5]; delete q;
*p = 20; delete p;
P. Q. R.
int x = 5; int x = 5; int x = 5;//address 0x50
int * p = &x; int * p = new int; int y = 10;//address 0x54
delete p; *p = 10; int * p = &x;
p = &x; int ** r = &p;
delete p; **r = 99;
cout << p << *p;
*r = &y;
cout << p << *p;

CMP1020/CMPN103 1/10
Programming Techniques Sheet #1 - Solution

2. [Pointer Arithmetic] Consider the following piece of code

int A[10] = {1, 10, 20, 30, 40, 50, 60, 70, 80, 90};
int *B;
int *C;
B = &A[2]; Commented [E2]: B = &A[2];
C = A+6; B becomes the name of the array portion that starts at the
A[2] to the last element, so, B[0] is the same as A[2].
Commented [E3]: C = A+6;
Assume that the array "A" is stored at address 100 and the size of the int is 4 bytes. C becomes the name of the array portion that starts at the
A[6] to the last element, so, C[0] is the same as A[0].
Complete the following table:
Commented [E4]:
Note that in general addresses are numbers.
Item Value Item Value When we wrote it in labs as 0x90 for example, that was also a
number but in Hexadecimal number system (not decimal).
A 100 B 108
&A[0] 100 C 124 Although addresses are after all numbers, the data type of
addresses must contain (*) after the data type of the
*A 1 C-B 4 variable stored in this address, like: int * or char *, …etc.
A[0] 1 B[0] 20 Commented [E5]:
*&A[0] 1 C[2] 80 B = &A[2];
So,
&*A 100 *(B+1) 30 B equals: 100 + 2 * size of elements (4 bytes here) = 108
A[0]+7 8 *B+1 21
Commented [E6]: C - B
A+2 108 *(&C[1]+1) 80 C – B = (124 - 108) / the size of the elem. (4 bytes here) = 4
which means:
*(A+7) 70 *&C[1]+1 71 Pointer1 – Pointer2 = Number of elements (not number of
&A[2] 108 *A**B**C 1200 bytes)
&A[6] 124 Commented [E7]: *&A[0]
*& Cancelled each other.
Commented [E8]: A + 2
(A + 2) is 108 Not 102.
because when you add:
Pointer + Number
in the code, the result will be:
Pointer + Number * No. Of Bytes of the Element Type (4
here)

So, the Number you add to the Pointer in the code is not the
number of bytes but number of elements.
Commented [E9]: *(&C[1]+1)
&C[1] is the address of element A[7]
(&C[1] + 1) is the address of element A[8]
*(&C[1]+1) is A[8]
Commented [E10]: *(A+7)
*(A+7) is the same as A[7]
Commented [E11]: &A[2]
&A[2] is the same as (A+2)
Commented [E12]: *A**B**C
The asterisk (*):
When it comes immediately before a pointer means
dereference operator (to reach the value that the pointer
points to) and when it comes between 2 numbers means
multiplication.
*A**B**C is the same as (*A)*(*B)*(*C)

CMP1020/CMPN103 2/10
Programming Techniques Sheet #1 - Solution

3. What is the output of the following piece of code?


a. [Pointer Arithmetic]

int A[5] = {0, 1, 2, 3, 4};


for(int* P=A; *P<4; P++) Commented [E13]: int* P=A
cout<<P<<"\t"<<*P<<endl; P now points to the first element too.
//Assume Array A is stored at address 100. Commented [E14]: *P<4
It means enter the loop as long as the element value that P is
currently pointing < 4 (get out of the loop once you find an
element >= 4)
Output:
100 0 Commented [E15]: P++
Increments the pointer one element (makes it points to the
104 1 next element).
108 2
112 3

b. [Alias Variables]

int x = 5; //Assume that x is stored at address 1000


cout<<"Address of x="<<&x<<", Value of x="<<x<<endl;
int &y = x; Commented [E16]:
cout<<"Address of y="<<&y<<", Value of y="<<y<<endl; int & y = x;
y = 10;
cout<<"Value of y="<<y<<", Value of x="<<x<<endl; Here, y is an alias (new name) to x, so same memory
location (no new location is allocated).

Output: The concept of alias variables is what is applied in pass by


reference (by alias).
Address of x=1000, Value of x=5
Address of y=1000, Value of y=5 [Note 1]: alias variable must be initialized (= x here) in the
Value of y=10, Value of x=10 same line of the declaration.
int & y; → Error
y = x;
4. What is the problem of the following pieces of code?
a. [Note 2]:
int & y = 5; → Error
why? → THINK
int A[5] = {0, 1, 2, 3, 4};
int B[5] = {5, 6, 7, 8, 9};
int *P;
P=B;
A=P;

Problem:
A = P; // Compilation error. yes A is a pointer to int like P
// but A is a constant pointer ➔ can’t change its value (the
address it points to).
b.

int* f)(
{
int x=90;
int *p=&x;
return p;
}

Problem: “Returning the address of an automatic variable”. Pointer p


points to a memory location that will be freed once the function exits.

CMP1020/CMPN103 3/10
Programming Techniques Sheet #1 - Solution

Commented [E17]:
Constants can be initialized once then never modified.
Note: Initialization of const. variable must be in the same line
of declaration.
Commented [E18]: int * const p = &x;
c. [Const. Pointer and Pointer to Const.] Here, p is a const. pointer
(the const. immediately before the pointer name).
1) int x = 10, y = 20; It means the pointer itself is const. (cannot point to another
2) const int z=30; location other than the initial location it pointed to).
3) int * q;
4) int * const p = &x; Cannot say: p = something; → Error
5) const int * r;
However, the const. pointer can change the value stored in
the location it’s already pointing to.
6) p = &y; ➔ can't change a const. pointer
7) r = &y; Can say: *p = y; → Correct
8) *p = 7; Note#1: constant pointers like any normal constant
9) *r = 9; ➔ r is a pointer to const. (can't change the pointee) variable must be initialized in the same line of declaration.
10) *q = 40; ➔ error (q is not initialized, “Bad Pointer”)
int * const p; → Error
p = &x;
11) z=50; ➔ can't change a const. variable
12) q = &z; ➔ q can't point to a const. var. because it can change it Note#2: automatic array’s pointer int A[10]; is a constant
pointer that’s why we cannot make A = something;
13) r = &z;
14) p = &z; ➔ can't change a const. pointer Commented [E19]: const int * r;
Here, r is a pointer to constant
(“const” anywhere before (*) → can be after or before “int”)
15) const int * const S = &y; const int * r; OR int const * r;
16) *S = 10; ➔ can't change the pointee of a pointer to const.
It means that the value it’s pointing to cannot be changed
17) S = &z; ➔ can't change a const. pointer using this pointer (maybe changed by other pointers but not
18) cout << S << “ ” << *S; by a pointer to const).

Cannot say: *r = something; → Error

Note: However, the pointer itself is NOT const. so it can point to


other locations.
The error text is the same if you made any of the following: Can say: r = &y; → Correct
z = something; // z is a const. var.
Commented [E20]: [Line 9]:
p = something; // p is const. pointer Note that although r points to y, we can write:
*r = something; // r is a pointer to const. y = 9; → Correct
S = something; // S is const. pointer to const. obj. But not:
*r = 9; → Error
*S = something; // S is const. pointer to const. obj. because any pointer to constant guarantees that the value
stored in the location it’s pointing to will not be changed by
[Error Text]: expression must be a modifiable lvalue this pointer but may be changed by any other way.
lvalue: means left hand side. Commented [E21]: [Line 13]:
The error means the LHS you wrote cannot appear in the LHS. Pointer to constant (like r) can point to const. objects (like
z) or non-const objects (like y).

However, it cannot change the value stored in the location it’s


pointing to in any of the two cases.

Const. objects (like z) can be pointed to ONLY by pointers


to const. (because they will not change them).
Commented [E22]: const int * const S = &y;
Here S is a constant pointer to constant object.
It is both const. pointer and pointer to const.

*S = something; → Error
S = something; → Error

It can point only to the initial location it pointed to and cannot


change the value stored in this location.
.
Commented [E23]: [Line 15]:
Here, S and *S can be used (read) but never modified
(written).

CMP1020/CMPN103 4/10
Programming Techniques Sheet #1 - Solution

5. Write function “Abs” that takes a float number and change it to its absolute value. If the number
is positive, it returns false indicating that it did not need to perform the absolute operation.
Otherwise, it changes the number to its absolute value and returns true.
Should we pass this number by value, reference or pointer? Why?
Write a main function that tests your function.

#include <iostream>
using namespace std;
bool Abs(float & x) // pass by ref.
{
if (x >= 0)
return false; // return will exit the func.
x = -x;
return true;
}
int main()
{
float a = 5.3;
bool b = Abs(a); // the function changes “a” itself if negative
if (!b) // (!b) means (not b)→ if b equals false, enter
cout << “Non-Negative!” << endl;
else
cout << “New Value = ”<< a << endl;
}

6. Write function “CountLessGreaterEq” that takes an array of integers and a value then outputs
3 counts: the count of elements less than the value, greater than the value and equal to the
value. Write a main function that tests your function.

Solution Notes:

The array should be allocated and filled in the “main” and be passed
to function ready to operate on it. The “main” function here will delete
this allocated array after last use of it.

The two proposed prototypes:


int CountLessGreaterEq(int * A, int n, int val, int & ls, int & grt); Commented [E24]:
OR . . . Use the return to return the equal count and pass the
void CountLessGreaterEq(int * A, int n, int val, int & ls, int & grt, int & remaining 2 counts by reference as a kind of output (when
you change them in the function, the corresponding empty
eql); variables that were sent to them from the main will change
too).

Pass by ref. (alias) creates an alias (new name) to the same


variable sent in the function call.
Here we propose one possible complete solution.
We used the three types of output from functions in this solution.
- Return Statement
- Pass by Reference (alias)
- Pass by Pointer

CMP1020/CMPN103 5/10
Programming Techniques Sheet #1 - Solution

#include<iostream>
using namespace std;

int CountLessGreaterEq(int * A, int asize, int val, int & L, int *pG)
{
// The three output counts (we used here 3 different ways of output)
int E = 0;// E for Equal elements count-> 1- return statement
L = 0; // L for Less elements count -> 2- passed by reference (alias)
*pG = 0; // *pG for Greater elements count -> 3- passed by pointer

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


{
if (A[i] == val)
E++;
else if (A[i] < val)
L++;
else // which means greater
(*pG)++; // the () is needed here before the ++
}
return E; // it is the only return of the function
}

int main()
{
// 1- allocate and read input array
int arr[5];
cout << "Enter Array Elements: " << endl;
for (int i = 0; i < 5; i++)
cin >> arr[i];
// 2- read the input value
int val;
cout << "Enter Value: " << endl;
cin >> val;
// 3- define output variables and call the func.
int ls, gr, eq;
eq = CountLessGreaterEq(arr, 5, val, ls, &gr);
// 4- print the output variables
cout << "less=" << ls << ", greater=" << gr << ", equal=" << eq << endl;
return 0;
}

7. Write function “ReplaceAll” that takes an array and two values, “oldV” and “newV”, and
replaces each occurrence of “oldV” in the array with value “newV” and returns the count of the
replaced elements. Write a main function that tests your function.

Solution Notes:

The array elements changed inside the function will also be changed in
the original array of the main because elements are passed by pointer
(the array name) → do NOT need to pass the array pointer by ref to Commented [E25]: Note:
change the elements. In the labs if you pass variables by reference without a need,
you will be penalized.

The array pointer here does not need to be passed by ref because we
will not make it point to another location (to NULL or a newly allocated
memory) inside the function.

CMP1020/CMPN103 6/10
Programming Techniques Sheet #1 - Solution

8. Write function “IsEven” that takes an array of positive integers and outputs a boolean array of
the same size of the input array. Each element of the output array contains true if the
corresponding element of the input array is even, otherwise, false. Write a main function that
tests your function.
#include <iostream>
using namespace std;

bool* IsEven(int * arr, int n)


{
bool * outArr = new bool[n];
for(int i = 0; i < n; i++)
{
if (arr[i] % 2 == 0) // even Commented [E26]:
outArr[i] = true; (%): the Mod operator → division “remainder”.
else
outArr[i] = false;
}
return outArr;
}
int main()
{
int A [] = {4, 5, 3, 1, 8};
bool * B;
B = IsEven(A, 5);
// [TODO]: make a for loop to print B’s elements Commented [E27]: [TODO] Left to you to do it.
delete [] B;
Commented [E28]: [Note#1]:
} We allocated A automatically here, so don’t need delete.

9. Write a function “SwapArr” that swaps two dynamically allocated integer arrays but without [Note#2]:
actually copying array elements from one place to another. We allocated B dynamically (with new) inside the function
because it’s the output array of the function, so one of the
jobs of the function is to allocate the array inside it.
Solution:
[Note#3]:
void SwapArr(int* &P, int* &R) The main deallocated B after last use of it (doesn’t need it
anymore).
{ int *T = P;
P = R; // (this line is why P is sent by ref.) In labs/exams/project if you forget any needed
R = T; // (this line is why R is sent by ref.) deallocation, you will be penalized.
} Commented [E29]: Only swap the array pointers while
passing them by ref.

10. Write a function “AlternateSplit” that takes an array “A” of size n and splits it into two arrays “B”
and “C”. Your function should
a. Create two dynamic arrays “B” and “C”.
b. Copy elements from array “A” to “B” and “C” alternatively (one to “B” then one to “C”
and so on).
c. Free the array “A” and make “A” points to NULL.
Write a main function that tests the function.

Solution:

void AlterSplit(int *&A, int size, int *&B, int &n, int *&C, int &m)
{
m = size/2; // the smaller size (of array C)
Commented [E30]:
n = size - m; Better to replace these 2 lines with:

// Dynamic Allocation (that's why B and C are sent by ref.) B = (n > 0)? new int[n] : NULL;
B = new int[n]; C = (m > 0)? new int[m] : NULL;
C = new int[m]; To allocate only when the no. of elements > 0.

// Filling Arrays The question mark (?) and th Colon ( : ) are with the “ternary
operator” → Search about it (self-study).

CMP1020/CMPN103 7/10
Programming Techniques Sheet #1 - Solution

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


{
if (i % 2 == 0) // even i
B[i/2] = A[i];
else
C[i/2] = A[i];
} // this will work on even or odd A’s size.

// Freeing the array, A


delete [] A; // don't forget deleting before setting to NULL Commented [E31]:
// don't forget the brackets [] Deleting the array doesn’t need the array pointer to be
A = NULL; // don't forget to set A to NULL after deleting passed by ref because you don’t make it point to another
location but will delete the location it’s already pointing to.
// (this line is why A is sent by ref. not the delete)
} Commented [E32]:
int main() That’s why we passed A by ref.
{ Note:
int size; A = NULL; does NOT delete the array but make A points
// [TODO] Read the size from the user to NULL.
int * A;
If you set A = NULL ; without deleting A before, this will
// [TODO] Allocate A dynamically
make A points to NULL and the allocated array elements will
// [TODO] Fill A’s Elements have NO pointer pointing to them, so can NEVER be deleted
// Declare the variables that will be sent by ref. after that.
// and not declared before
int n, m; [The Rule]: Any dynamically allocated memory should
have at least one pointer pointing to it to be able to delete
int * B, * C; it.
// Call the function
AlterSplit(A, size, B, n, C, m);
// After fn. Call, A is deleted and pointing to NULL
// B and C arrays are allocated (or NULL in the special case)

// [TODO] Print B’s Elements (if B is not NULL) and same for C
// [TODO] Deallocate B (if not NULL) and same for C Commented [E33]:
} Note that:
A is allocated in main and deallocated in func. (as required).
B and C are allocated in func. and deallocated in main.
Another Solution (More Difficult):
If it is not required in the question to deallocate A in the
function, it is more logical to deallocate it inside the main
void AlternateSplit(int* &A,int* &B,int* &C,int n) but since it’s required, make it inside.
{
int i,j;
//Dynamically allocate memory for B & C
B=new int[(n+1)/2]; // n+1 to account for odd values for n.
C=new int[n/2];

for(i=0,j=0; i<n/2; i++,j+=2)


{
*(B+i)=*(A+j); //Same as B[i] = A[j]
*(C+i)=*(A+j+1);//Same as C[i] = A[j+1]
}
if(j<n) //n is odd one element remaining
*(B+i) = *(A+j);//B[i] = A[j]

//Free Pointer A and set it to NULL


delete []A;
A=NULL;
}

11. Write function “CountOccurrences” that takes a sorted array, “Input”, and counts the number Commented [E34]:
of occurrence of each element in the array. It outputs two arrays: Solution:
In the slides of: “Introduction to Algorithms”
a. “Unique” array that contains the unique elements of the input array, lecture.
b. “Freq” array that contains the number of occurrence of each element in the input array.
Write a main function that tests your function. (Assume that the input array is entered sorted!)

CMP1020/CMPN103 8/10
Programming Techniques Sheet #1 - Solution

12. Write the following functions to deal with character arrays: Commented [E35]:
a. Function “GetCopy” that takes a word and returns a new copy of this word. [Char Variable]: ---------

b. Function “GetFullname” that takes the first name and the second name of a person and char c = ‘s’; // single quotes with characters
returns his full name.
[Char Array]: ---------
c. Function “PrintSorted” that takes 2 words and print them sorted ascendingly
alphabetically. If the 2 words are the same, the function should print it once. char word [] = “sheet”; // double quotes with char arrays or
Assume that the function is case sensitive, so “sheet” is different from “Sheet” and in strings
this case the function should print them “Sheet” then “sheet” (the default ASCII sorting). The above statement will allocate 6 characters: 5 for the word
d. A main function that tests the above 3 functions. Do not forget any needed and 1 for null character (null terminator) ‘\0’ (not related to
deallocation. NULL pointer we studied before).

Null terminator is a character inserted after the actual


Solution: characters of the char array indicating the end of the filled
characters.
#include <iostream>
#include <cstring> // to use char array functions like strlen, ...etc The built-in char array functions use the null terminator to
using namespace std; know the end of the filled characters (because maybe a larger
array with max size is allocated but not all the array elements
is filled).
char * GetCopy(char * input)
So, the above array could be written like this (another way):
{ char word [] = { ‘s’, ‘h’, ‘e’, ‘e’, ‘t’, ‘\0’}; // single ‘ with
int len = strlen(input); characters
char * copy = new char[len + 1]; // + 1 for the null char
strcpy_s(copy, len + 1, input); Commented [E36]:
In out written exams, you must use char arrays (NOT
return copy; strings) to represent text. However, in the labs or the
} project, you’re free to use whatever you want.
Commented [E37]:
char * GetFullname(char * fname, char * sname) The ASCII code of the capital letters is smaller than the
{ ASCII of the small letters.

int flen = strlen(fname); Commented [E38]: char * GetCopy(char * input)


Note: When you pass or output character arrays, you don’t
int slen = strlen(sname); need to pass the no. of characters because you can get it
int fullsize = flen + slen + 2; // + 1 for the null char using strlen function.
// + 1 for the space ' ' between fname and sname Commented [E39]: strlen
char * fullname = new char[fullsize]; Returns the number of actual characters without (excluding)
// 1- copy fname in fullname the null character.

strcpy_s(fullname, fullsize, fname); Commented [E40]: strcpy_s


Copies the “input” in “copy”.
// 2- add (append or concatenate) a space
strcat_s(fullname, fullsize, " "); // the result is saved in: The underscore s (_s) in strcpy_s is the safe version of the
// the input fullname itself (not returned) old strcpy.

// 3- append sname to fullname Read the difference between the 2 versions here (self-study):
strcat_s(fullname, fullsize, sname); http://www.cplusplus.com/forum/beginner/118771/
return fullname; The safe version takes the 2nd argument (the max size of the
} destination array).

The lecture slides use the old version.


void PrintSorted (char * word1, char * word2)
Commented [E41]: strcat_s(fullname, fullsize, "
{ ");
cout << "The words sorted ascendingly alphabetically: "; The space here should be in double quotes because
strcpy_s takes char arrays (not characters) as input.
int out = strcmp(word1, word2); “ ” is char array that contains 1 char ‘ ‘ then null terminator.
if (out == 1) Commented [E42]: strcmp
cout << word2 << ", " << word1 << endl; Compares word1 with word2 and returns:
else if (out == -1) 0 → if they are equal
1 → if word1 > word2 (in alphabetical order)
cout << word1 << ", " << word2 << endl; -1 → if word1 < word2
else // means out == 0
cout << word1 << endl;
}

CMP1020/CMPN103 9/10
Programming Techniques Sheet #1 - Solution

int main()
{
// --- Function # 1 -----------------------------

// 1- allocate first automatically (max 25) and read it form the user
char first[25]; Commented [E43]: char first[25];
cout << "Enter first: "; The maximum size of the actual characters is 24 not 25 (the
last one is left for the null terminator).
cin >> first;
Commented [E44]: cin >> first;
[Note #1]:
// 2- call copy function to copy first name in fcopy Don’t need a loop to read/write each character of char array
char * fcopy; // to receive the output of the function (unlike arrays of other types).
fcopy = GetCopy(first); // is there a problem with simply making: fcopy = first; ? cin >> first; → reads chars then add null terminator auto.
cout << first; → prints characters till it finds null terminator
// 3- display the copy [Note #2]:
cout << "The copy: " << fcopy << endl; The entered name here may be less than 24 which is fine
because cin with char array adds the null terminator after
the actual chars it read from the user.
// 4- change fcopy and display first
cout << "Change the copy (choose no. chars <= no. chars of the old copy): "; [Note #3]:
cin >> first; reads the characters that the user enter before
cin>> fcopy; the white space (it takes one word).
cout << "First: " << first << endl;
If you want to read the whole line that may contain more than
one word (contain white spaces), you can use getline;
// 5- deallocate the copy
delete [] fcopy; cin.getline(first, 24);

Sometimes you need to use: cin.ignore(); before getline.


// --- Function # 2 ----------------------------- Search why? (self-study)
Commented [E45]: fcopy = GetCopy(first);
// 1- allocate second automatically (max 25) and read it form the user If you replace the GetCopy call with this statement:
char second[25]; fcopy = first;
this will NOT allocate a new array to store the copy but make
cout << "Enter second: "; “fcopy” points to the original array with “first”, so if the array
cin >> second; characters are changed using any of them (“fcopy” or “first”)
the array of the other pointer will be affected because it’s the
same array after all.
// 2- call GetFullname
char * full = GetFullname(first, second); Instead, the function GetCopy that we implemented
allocates new array dynamically then copies the character
inside it.
// 3- display full name Commented [E46]: cout << "First: " << first <<
cout << "Full Name: " << full << endl; endl;
“first” wasn’t changed because “fcopy” points to another
array.
// 4- deallocate full name
delete [] full; However, if you make fcopy = first; instead of using our
GetCopy function, you will find “first” array is changed too
because it’s the same array pointed to by “fcopy”.
// --- Function # 3 -----------------------------
Commented [E47]:
Do NOT forget to deallocate any dynamically allocated
// 1- allocate and read the 2 words memory.
char word1[100];
char word2[100];
cout << "Enter word 1: ";
cin >> word1;
cout << "Enter word 2: ";
cin >> word2;

// 2- call Print Words


PrintSorted(word1, word2);
}

CMP1020/CMPN103 10/10

You might also like