I'm trying to write my own strcat function in C++, but it has some problems.
My input is two chars c and a, and my function will return a char pointer to a char which c is concatenated with a.
For example,
Input: 'abc' 'xyz'
Expected Output: 'xyzabc'
My function's Ouput: 'xyza@▲∩'
My function returns some special character different to my input.
I debugged my function and found that:
- When
i=0,destination[3]=source[0]='a' - But when
i=1,destination[8]=source[1]='b' - And when
i=2,destination[9]=source[2]='c' - Finally,
destination[10]='\0'
#include<iostream>
#include<string.h>
using namespace std;
char* mystrcat ( char * destination, const char *source){
for (int i=0; i<strlen(source); i++) {
destination[strlen(destination)+i] = source[i];
}
destination[strlen(destination)+strlen(source)]='\0';
return destination;
}
int main() {
char c[100];
cin.getline(c, 99);
char a[100];
cin.getline(a,99);
mystrcat(a,c);
cout<<a;
return 0;
}
strlenreturns the length from the pointer to the first\0it encounters. Here, during the loop, you overwrite this character in thedestinationpointer, so subsequent calls tostrlenwill return the length to some random point in memory that happens to hold this character.One easy fix is to extract the
strlenresults before you start modifying strings: