@kemort: even worse. s2 is not even valid pointer, and why did you change his function which was completely fine and actually resembles real implementation?
#include <iostream>
usingnamespace std;
void stringcpy(constchar* src,char* dest){
while(*src != '\0'){
*dest++ = *src++;
}
*dest = '\0'; //since the '\0' from src is not copied to dest, add it manually to end dest.
//remember that dest is no longer at the beginning but at the end.
}
int main()
{
constchar str[] = "fatima";
// char str2[] = ""; can hold only one character.
char str2[sizeof(str)]; //make it hold the same number of characters as the source, including the ending NULL char.
constchar* s = str;
char* s2 = str2;
stringcpy(s, s2);
cout<<str2<<" ";
cout<<str;
}
Yes, that code does not copy null teminator so you need to place it manually.
Compiler does not do this automaticly (it actually cannot read minds and know that you want it) and that is why you see garbage when outputting non-terminated string.
Yes there is a need.
There is no string without the ending null character and the compiler will not put it for you in this case.
Without that line, dest will simply be an an array of characters .
e.g
1 2 3 4 5 6
char string[5] = "Bill"; //equivalent to char string[5] = {'B','i','l','l','\0'}, this is a string.
char noString[4] = {'B','i','l','l'}; //simple array of characters as a result of removing line 8
std::cout<<string; //good
std::cout<<noString //not good. ==> garbage (except overloaded properly)