The funciton my_strcpy(char dest, const char cource) is to copy "hello world" from source to dest. Do not use the library. The copy process will only stop at the last "\0". Make sure dest is large enough to any lenght of sentence inputted. The following is my code. The program copy the first letter of "hello world" which is "h", but the requirement is to copy the whole sentence "hello world". Thank you for your helps
#include <iostream>
using namespace std;
void my_strcpy(char dest[],const char source[]) {
int i = 0;
while (source[i] != '\0') {
dest[i] = source[i];
++i; }
dest[i] = '\0';
}
int main( ){
char dest;
char source[]="hello world";
my_strcpy(&dest,source);
cout<<"Destination now : "<< dest << endl;
return 0;
}
There is a very small logical error in the code provided here.
Characters in c++ are 1 byte long, character arrays are more than 1 byte.
So, to store "hello world" we need a character array and not just a character.
Thus we have to declare an array of characters big enoung in place of just a character to accomodate the complete string "hello world" like this, char dest[20];
Also now when passing the argument in the funtion we need to only write my_strcpy(dest,source); and not my_strcpy(&dest,source); because the name of an array points to the location of the first element of the array ie &dest[0], thus my_strcpy(&dest[0],source); will also work.
Here is the complete rectified code
//These are the required header file
#include <iostream>
using namespace std;
//No changes needed here
void my_strcpy(char dest[], const char source[])
{
int i = 0;
while (source[i] != '\0')
{
dest[i] = source[i];
++i;
}
dest[i] = '\0';
}
int main()
{
//Making the destination array now so that we can store the string
char dest[20];
char source[] = "hello world";
//Passing the argument as dest in place of &dest
//my_strcpy(&dest[0], source); will also work fine, but it is lengthy
my_strcpy(dest, source);
//Now this will show the correct output
cout << "Destination now : " << dest << endl;
return 0;
}
Here is the image of the code to help understand indentation
Here is the output
NOTE: If you liked the answer a thumbs up would make my day :) Have a nice day.
Get Answers For Free
Most questions answered within 1 hours.