Write a program in C to dynamically allocate some char buffe

Write a program in C++ to dynamically allocate some char buffers, uses memset to fill them , and use memcpy and memmove to move the data arround

Part 3a.

a.     Allocate 2 char buffers of 128 bytes each using malloc.  Call your pointers thing1 and thing2 (in memory of Dr. Seuss, of course!)

b.     Initialize all 128 bytes of thing1 to asterisks (‘*’) using memset.

c.     Set the 21st  byte to a null char (‘\\0’).  This will make the buffer contain a c-string of 20 asterisks (and terminated by the null char).

     thing1[20] = ‘\\0’;   // this will do it!  
     memset(thing1+20, 0, 1); // this will also do it (why?)

d.     Use memset to set bytes 22-25 of  thing1 to percent signs.

e.     Print thing1  to the console using cout.  You should get only a string of 20 asterisks.

f.      Set the 42nd byte to a null char, and then
     cout << (thing1+22) << endl;
You should get your percent signs, followed by some asterisks, because you created a 2nd c-string starting at byte 22.

g.     Print the numeric values of the first 50 chars;  this will show you that your array contains 20 asterisks (42), a null char (0)  flagging the end of the c-string, 4 percent signs (37) and more asterisks.

Solution

#include<iostream>

using namespace std;

int main()
{
   char *thing1, *thing2;

   //part a initialization
   thing1 = (char*)malloc(128);
   thing2 = (char*)malloc(128);
   //b use memset
   memset(thing1,\'*\',128);
   memset(thing2,\'*\',128);
   //Set the 21st byte to a null char (‘\\0’).
   thing1[20] = \'\\0\';
   memset(thing1+20, 0, 1);
   //Use memset to set bytes 22-25 of thing1 to percent signs.
   for(int i =22; i <=25; i ++)
       memset(thing1+i,\'%\',1);
   //Print thing1 to the console using cout
   cout<<\"print thing1 after seeting 22-25 \'to %\'= \"<<thing1<<endl;
   //Set the 42nd byte to a null char
   memset(thing1+42,char (0),1);
   cout<<\"thing1 after setting to 42 byte to null = \"<<thing1<<endl;
   cout << (thing1+22) << endl;
   //Print the numeric values of the first 50 chars;
   cout<<\"try to print values of the first 50 chars\ \";
   int value;
   for(int i = 0 ; i < 50 ; i++)
   {
       value = *(thing1+i);
       cout<<\"value of char\"<<i<<\" = \"<<value<<endl;
   }
   cout<<endl;

}

Write a program in C++ to dynamically allocate some char buffers, uses memset to fill them , and use memcpy and memmove to move the data arround Part 3a. a. All
Write a program in C++ to dynamically allocate some char buffers, uses memset to fill them , and use memcpy and memmove to move the data arround Part 3a. a. All

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site