fork download
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <stdlib.h> // Required for malloc
  4.  
  5. #define MAX 20
  6.  
  7. char *concatena(char *s1, char *s2);
  8.  
  9. int main() {
  10. char s1[MAX], s2[MAX];
  11.  
  12. printf("Inserisci la prima stringa: ");
  13. scanf("%s", s1);
  14.  
  15. printf("Inserisci la seconda stringa: ");
  16. scanf("%s", s2);
  17.  
  18. char *tot = concatena(s1, s2);
  19.  
  20. printf("Stringa totale: %s\n", tot);
  21.  
  22. free(tot); // Free dynamically allocated memory
  23. return 0;
  24. }
  25.  
  26. char *concatena(char *s1, char *s2) {
  27. int l1 = strlen(s1);
  28. int l2 = strlen(s2);
  29.  
  30. // Allocate enough memory for both strings + null terminator
  31. char *concatenata = malloc(l1+l2+1 *sizeof(char));
  32. if (concatenata == NULL) {
  33. printf("Errore di allocazione memoria!\n");
  34. exit(1); // Exit if memory allocation fails
  35. }
  36.  
  37. // Copy the first string
  38. for (int i = 0; i < l1; i++) {
  39. concatenata[i] = s1[i];
  40. }
  41.  
  42. // Append the second string
  43. for (int i = 0; i < l2; i++) {
  44. concatenata[l1 + i] = s2[i];
  45. }
  46.  
  47. // Null-terminate the string
  48. concatenata[l1 + l2] = '\0';
  49.  
  50. return concatenata; // Return the dynamically allocated string
  51. }
  52.  
Success #stdin #stdout 0.01s 5324KB
stdin
Standard input is empty
stdout
Inserisci la prima stringa: Inserisci la seconda stringa: Stringa totale:  �԰�