C What is the output of the following code segment NOTE size

C++: What is the output of the following code segment? (NOTE: sizeof() returns the number of bytes the variable uses in memory) Please provide explanation for the answer chosen.

int maxChars; const int SIZE 1-25; const int SIZE2-25; char string1 [SIZE1] - \"Justice League: \'\' ; char string2 [SIZE2] = \" Battle for Metropolis\"; maxchars = sizeof (string!) - (strlen (string1) + 1); strncat (stringl, string2, maxChars); cout

Solution

Here is the code explained for you:

#include <cstring>
#include <iostream>
using namespace std;
int f(int a, int b)
{
return a;
}
int main()
{
int maxChars;           //Declares an integer maxChars.
const int SIZE_1 = 25;   //Declares a const integer SIZE_1
const int SIZE_2 = 25;   //Declares a const integer SIZE_2
char string1[SIZE_1] = \"Justice League:\";   //Declares and assigns a character array string1.
char string2[SIZE_2] = \"Battle for Metropolis\";   //Declares and assigns a character array string2.
maxChars = sizeof(string1) - (strlen(string1) + 1);   //sizeof(string1): string1 is having a total of 25 bytes, and sizeof each int is 1 byte.
//So, sizeof string1 is 25.
//strlen(string1) is the number of actual characters in the string. It has 14 characters.
//So, maxChars is assigned a value 25 - 15 = 10.
strncat(string1, string2, maxChars); //strncat appends not more than maxChars(10) from string2 to string1.
//So, string1 will now become, Justice League:Battle fo.
cout<<string1<<endl;   //So, it now prints the above specified string: Justice League:Battle fo
}

C++: What is the output of the following code segment? (NOTE: sizeof() returns the number of bytes the variable uses in memory) Please provide explanation for t

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site