Why some character can't be edited in C++?

208 Views Asked by At

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;
}
2

There are 2 best solutions below

6
Mureinik On

strlen returns the length from the pointer to the first \0 it encounters. Here, during the loop, you overwrite this character in the destination pointer, so subsequent calls to strlen will return the length to some random point in memory that happens to hold this character.

One easy fix is to extract the strlen results before you start modifying strings:

char* mystrcat (char *destination, const char *source) {
    int destLen = strlen(destination);
    int srcLen = strlen(source);
    for (int i = 0; i < srcLen; i++) {
        destination[destLen + i] = source[i];
    }
    destination[destLen + srcLen] = '\0';
    return destination;
}
2
Ashna Mittal On

Given below is the correct implementation of the code.

#include<bits/stdc++.h>
using namespace std;
void mystrcat ( char* destination, const char *source){
    int p;
    for(p=0; destination[p] != '\0'; p++);//pointing to the index of the last 
    character of x

    for(int q=0; source[q] != '\0'; q++,p++)
    {
    destination[p]=source[q];
    }
    destination[p]='\0';
    }
int main() {
   char c[100];
   cin.getline(c, 99);
   char a[100];
   cin.getline(a,99);
   mystrcat(a,c);
   cout<<a;
   return 0;
 }

As the length of source will get updated in your code, it gives special symbols as output.