0

Code to concatenate strings

 #include<stdio.h> char *concat(char *p1,char *); //function decalaration int main(void) { char a[100],b[100],*q=NULL; //declare two char arrays printf("Enter str1:"); scanf("%s",a); printf("Enter str2:"); scanf("%s",b); q=concat(a,b); //calling str concat function printf("Concatenated str:%s\n",q); return 0; } char *concat(char *p1,char *p2) //function to concatenate strings { while(*p1!='\0') p1++; while(*p2!='\0') { *p1=*p2; p1++; p2++; } *p1='\0'; printf("Concatenated str=%s\n",p1); //printing the concatenated string return p1; //returning pointer to called function } 

//Although the logic is correct but its not showing the output. //Why this code doesn't work?

4
  • 1
    In your concat function, when you do return p1, what is the value of *p1? Commented Nov 4, 2016 at 12:40
  • @gsamaras Not really bad, p1 still is pointing to a valid string. Commented Nov 4, 2016 at 12:43
  • Well yes @Someprogrammerdude, but not the one he wants.. ;) Commented Nov 4, 2016 at 12:52
  • a debugger will answer your question quite well Commented Nov 4, 2016 at 13:53

2 Answers 2

5

You are returning p1 which isn't pointing at the start of the concatenated string. You just need to save the original and return it.

 char *concat(char *p1,char *p2) //function to concatenate strings { char *org = p1; ... return org; } 
Sign up to request clarification or add additional context in comments.

2 Comments

Exactly. However, it would be nice to advice the OP to use a piece of paper and draw what he is code does! It's obvious..And he will learn. :)
Be aware that your function suffers the problem that the standard strcat() function does.
1

You can try this:

#include <stdio.h> #include <stdlib.h> #include <string.h> #define MAXCHAR 100 void trim_newline(char *str); char *concatenate(const char *str1, const char *str2); void exit_if_null(void *ptr, const char *msg); int main(void) { char str1[MAXCHAR], str2[MAXCHAR]; char *concat; printf("Enter str1: "); if (fgets(str1, MAXCHAR, stdin) != NULL) { trim_newline(str1); } printf("Enter str2: "); if (fgets(str2, MAXCHAR, stdin) != NULL) { trim_newline(str2); } concat = concatenate(str1, str2); printf("Concatenated str:%s\n",concat); free(concat); return 0; } void trim_newline(char *str) { int length = strlen(str) - 1; if (str[length] == '\n') { str[length] = '\0'; } } char *concatenate(const char *str1, const char *str2) { char *result; result = malloc(strlen(str1) + strlen(str2) + 1); exit_if_null(result, "Initial Allocation"); strcpy(result, str1); strcat(result, str2); return result; } void exit_if_null(void *ptr, const char *msg) { if (!ptr) { printf("Unexpected null pointer: %s\n", msg); exit(EXIT_FAILURE); } } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.