Yeah this is a simple question and pretty popular. And this is what I did.
There is a segmentation fault when we copy characters from src
into dest
. Now, I can understand the source of this fault - when we iterate over the dest
string we reach the end and then the dest
pointer points to the 'string terminator' or 0. So next when we put *dest++=*src++
it obviously will give an error.
//includes
void concat(char * dest, const char * src) {
while (*dest) ++dest;
while (*dest++ = *src++);
}
void main(){
concat("hi","hello");
getch();
}
The only way to beat this is to preallocate memory equal to the sum of both the strings - but that kind of beats the purpose of this method. And secondly I have searched online and found similar codes.
What am I missing?