1

My assignment is to concatenate v1 onto v2 and the function my_strcat() has to be void. How can I use a void function to return the concatenated strings?

int main(void){
    char v1[16], v2[16];
    int i1, i2;
    printf("Enter First Name: \n");
    scanf("%s", v1);
    printf("Enter Last Name: \n");
    scanf("%s", v2);
    i1 = my_strlen(v1);
    i2 = my_strlen(v2);
    printf("len: %3d - string: %s \n", i1, v1);
    printf("len: %3d - string: %s \n", i2, v2);
    my_strcat(v1, v2);
    printf("Concatenated String: %s \n", v1);
    return 0;
}

void my_strcat (char s1[], char s2[]){
    int result[16];
    int i = 0;
    int j = 0;
    while(s1[i] != '\0'){
        ++i;
        result[i]= s1[i];
    }
    while(s2[j] != '\0'){
        ++j;
        result[i+j] = s2[j];
    }
    result[i+j] = '\0';
}
Weather Vane
  • 33,872
  • 7
  • 36
  • 56
user4766244
  • 69
  • 1
  • 2
  • 8

1 Answers1

1
void my_strcat (char s1[], char s2[],char result[]){
    int result[16];
    int i = 0;
    int j = 0;
    while(s1[i] != '\0'){
        result[i]= s1[i];
        ++i;
    }
    while(s2[j] != '\0'){
        result[i+j] = s2[j];
        ++j;
    }
    result[i+j] = '\0';
}

You can do something like this..I main() declare a third result string whose size is size(v1)+size(v2)+1

char result[33];
my_strcat(v1,v2,result);

Output:

Enter First Name: avinash
Enter Last Name: pandey
len:   7 - string: avinash 
len:   6 - string: pandey 
Concatenated String: avinashpandey 
avinash pandey
  • 1,321
  • 2
  • 11
  • 15
  • So I need to add the `char result[]` to the function and declare a string in main like `result = v1[s1] + v2[s2] + 1` @avinashpandey.? – user4766244 Apr 02 '15 at 18:49
  • no not like that, take a look at code .What I meant that size of result string should be equal to grater than sum of both strings lengths.Declare result like a normal string but pass it to the function as my_strcat(v1,v2,result).As string is also an array it's get passed as reference , hence any change in result in the function will be reflected back in main(). – avinash pandey Apr 02 '15 at 18:53
  • When I run the program it gives me weird symbols for the concatenated string @avinashpandey. – user4766244 Apr 02 '15 at 19:03
  • It is because your logic was wrong I have edited in my answer – avinash pandey Apr 02 '15 at 19:08
  • How can you take away `char result[]` from the functuin `my_strcat` but still have it? – user4766244 Apr 02 '15 at 19:12
  • Its because result[] is declared in main() I am just passing it to my_strcat.I hope you get the logic... – avinash pandey Apr 02 '15 at 19:15