How do I concatenate a string without using the functions of the string library?

Asked

Viewed 141 times

-1

#include <stdio.h>

void concatenar (char str1, char str2){
    int c, a;

    for(c=0; str1[c]!='0'; c++)

    for(a=0; str2[a]!='0'; a++){
        str1[c]=str2[a];
    }
    return str1;
}
int main (void){
    char str1[10], str2[10];

    printf("Digite uma palavra: ");
    gets (str1);
    printf("Outra palavara: ");
    gets(str2);

    printf(void ("%s", str1));

    puts(concatenar(str1, str2));
    return 0;
}

1 answer

0

I made some corrections in your code, tested and was working, but before some observations:

In C++, if it is really C++ and not C89 as it appears, it would be preferable to use a std::string (where the attention can be made with the operator +).

And it is definitely not advisable to use the function gets(), because it is insecure, since it does not check the array boundaries, having been inclusive removed in C11.

That said, let’s go to the code:


#include <stdio.h>

char* concatenar (char str1[], char str2[]){

   int c, a;
   for(c = 0; str1[c] != '\0'; c++){}

   for(a = 0; str2[a] != '\0'; a++, c++){
      str1[c] = str2[a];
   }

   str1[c] = '\0';

   return str1;
}


int main (){

   char str1[100], str2[100];

   printf("Digite uma palavra: ");
   gets (str1);

   printf("Outra palavra: ");
   gets(str2);

   puts(concatenar(str1, str2));
   return 0;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.