-2

This code want to concate the string but it do not show the output

#include<stdio.h>
#include<string.h>
main( ) 
    {  
    char *str1 = "United" ;  
    char *str2 = "Front" ;  
    char *str3 ;  
    str3 = strcat ( str1, str2 ) ;  
    printf ( "\n%s", *str3 ) ; 
    }

1 Answers1

1

I will list out the flaws in the code.

  1. "United" and "Front" are string constants, meaning they cannot be modified.
  2. strcat adds the second string to the first, as the first input is a constant string the operation is not possible.
  3. printf just need the 'str3'.

There are 2 ways to correct the code, a) get the str1 through scanf b) get str1 by strcpy

I have provided the second solution, also str1 & str3 will both have the final answer.

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
main( )
{
        char *str1=malloc(20 * sizeof(char));
        char *str2 = "Front" ;
        char *str3 ;
        if(str1){
                strcpy(str1,"United");
                str3 = strcat ( str1, str2 ) ;
                printf ( "%s\n", str3 ) ;
                free(str1);
        }
        else{
                printf("malloc failure!\n");
        }
}

With reference to the comments I have added a version without dynamic memory allocation:

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main( )
{
        char str1[20];
        char *str2 = "Front" ;
        char *str3 ;
        strcpy(str1,"United");
        str3 = strcat ( str1, str2 ) ;
        printf ( "%s\n", str3 ) ;
}
M. Knight
  • 89
  • 5