user12291200
user12291200

Reputation:

What's wrong here? I'm not getting my string concatenated?

I have written this code from an algorithm given by my friend. But when I try to implement it it's not working. Can anyone tell me error here?

#include<stdio.h>
void scat(char [], char []);
int i,j;
void main()
{

    char s1[10],s2[10];
    printf("Enter first string: ");
    scanf("%s",&s1);

    printf("Enter second string: ");
    scanf("%s",&s2);

    scat(s1,s2);
}

void scat(char s1[], char s2[])
{
    char str1[10],str2[10],str3[20];

    for(i=0;str1[i]!=NULL;i++)
        str3[i]=str1[i];

    for(j=0;str2[j]!=NULL;j++,i++)
        str1[i]=str3[j];

    printf("\nConcanated string is %s",str3);
}

Upvotes: 0

Views: 103

Answers (3)

PrunePudding
PrunePudding

Reputation: 1

for c, strings are simply a pointer to char arrays, so they can't really be concatenated. but we can combine them in another way. we can use strcat from the string.h library. this works:

#include <stdio.h>
#include <string.h>
#define MAX_LIMIT 200

int main() {    char str1[200], str2[200];

    printf("Enter the first string: ");     
    fgets(str1, MAX_LIMIT, stdin);

    printf("Enter the second string: ");    
    fgets(str2, MAX_LIMIT, stdin);

    strcat(str1, str2);

    printf("\nConcanated string is %s", str1);

    return 0; }

Upvotes: 0

Nikhil Badyal
Nikhil Badyal

Reputation: 1697

What are you copying? str1 into str3 and str3 into s1. What does it mean ?. Even str1, str2 have nothing useful in them. Just unknown character so copying them is undefined. Try this.

void scat(char *s1, char *s2)
{
    char str3[20];

    for(i=0;s1[i]!='\0';i++){
        str3[i]=s1[i];}

    for(j=0;s2[j]!='\0';j++,i++)
        str3[i]=s2[j];

    str3[i]= '\0'; // This is must

    printf("\nConcatenated string is %s",str3);
}

Upvotes: 1

Maqcel
Maqcel

Reputation: 509

#include<stdio.h>
void scat(char [], char[]);
int main()
{

    char s1[10], s2[10];
    printf("Enter first string: ");
    scanf("%s", s1);

    printf("Enter second string: ");
    scanf("%s", s2);

    scat(s1, s2);
    return 0;
}

void scat(char s1[], char s2[])
{
    char str3[20];
    int i,j;
    for (i = 0; s1[i] != '\0'; i++)
        str3[i] = s1[i];

    for (j = 0; s2[j] != '\0'; j++, i++)
        str3[i] = s2[j];
    str3[i] = '\0';
    printf("\nConcanated string is %s", str3);
}

U used undeclared variables in function. Also I fix some mistakes you made.

Upvotes: 1

Related Questions