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';
}
4
  • Possible duplicate: stackoverflow.com/questions/308695/… Commented Apr 2, 2015 at 18:41
  • Just pass a buffer (e.g. an array) to the function to store the new string. Commented Apr 2, 2015 at 18:43
  • How can I do that? @teppic Commented Apr 2, 2015 at 18:45
  • @Cryptic - have a read up on passing arrays to functions. It's easy enough. Commented Apr 2, 2015 at 18:47

1 Answer 1

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 
Sign up to request clarification or add additional context in comments.

6 Comments

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.?
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().
When I run the program it gives me weird symbols for the concatenated string @avinashpandey.
It is because your logic was wrong I have edited in my answer
How can you take away char result[] from the functuin my_strcat but still have it?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.