Shubham S. Naik
Shubham S. Naik

Reputation: 341

Why this program doesn't print a concatenated string?

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?

Upvotes: 0

Views: 100

Answers (2)

RoadRunner
RoadRunner

Reputation: 26315

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

Upvotes: 1

P.P
P.P

Reputation: 121397

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

Upvotes: 5

Related Questions