1

I'm trying to implement strcat() in C but stuck on that the output result is repeated src.

here is my code.


void my_strcat(char des[], char src[]) {
    int i = 0, j = 0;
    while (des[i] != '\0')
        i += 1;
    while (src[j] != '\0') {
        des[i + j] = src[j];
        j += 1;
    }
    des[i + j] = '\0';

    printf("%s", des);
}

int main() {
   char des[1000], src[100];
   for(int i = 0; i < 2; ++i) {
        printf("src: ");
        scanf("%s", src);
        my_strcat(des, src);
    }
    
    printf("%s", des);

}

the output is not the same as I was expected before. It's like for example:

src: a src: b des: aabb

6
  • my_strcat doesn't return anything, yet ou use its return value here: printf("%s", my_strcat(des, src)). Didn't you get at least c compiler warning? Commented Apr 1, 2021 at 13:38
  • @Jabberwocky is was my typo! I just want to use void type. Commented Apr 1, 2021 at 13:39
  • 4
    You have to initialitze des. des[0]='\0'; Commented Apr 1, 2021 at 13:40
  • Then you probably want printf("%s", des). Commented Apr 1, 2021 at 13:41
  • @Holger I added but it still does not work. Commented Apr 1, 2021 at 13:45

1 Answer 1

1

You probably want this:

#include <stdio.h>
#include <stdlib.h>

void my_strcat(char des[], const char src[]) {   // better use const her
  int i = 0, j = 0;
  while (des[i] != '\0')
    i += 1;
  while (src[j] != '\0') {
    des[i + j] = src[j];
    j += 1;
  }
  des[i + j] = '\0';

  // printf("%s", des);  // dont print des here
}

int main() {
  char des[1000];
  char src[100];
  des[0] = 0;   // initialize des to a zero length string      
  for (int i = 0; i < 2; ++i) {
    printf("src: ");
    scanf("%s", src);
    my_strcat(des, src);
  }

  printf("%s", des);   // print the destination
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you so much! It worked. But please Could you explain why using printf() inside my_strcat() is not working?
@KeinKeinKein it is working, but it should not be there. After all your function is called my_strcat and not my_strcat_and_print_result
@KeinKeinKein The only relevant line is des[0] = 0;. When you initialize the destination, your example will work with or without the printf() call.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.