Activity6 - Angeline Evangelista

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 1

#include <stdio.

h>
#include <stdlib.h>
#include <string.h>

//Activity 6: Pointers and Malloc--Concatenate Strings


int main() {
char first_string[1000];
char second_string[1000];

printf("Enter the first string: ");


fgets(first_string, sizeof(first_string), stdin);
first_string[strcspn(first_string, "\n")] = '\0'; //terminate new line

printf("Enter the second string: ");


fgets(second_string, sizeof(second_string), stdin);
second_string[strcspn(second_string, "\n")] = '\0'; //terminate new line

size_t string1 = strlen(first_string);


size_t string2 = strlen(second_string);

char* concatenated_string = (char*)malloc(string1 + string2);


if (concatenated_string == NULL) {
fprintf(stderr, "Memory allocation FAILED!\n");
return 1;
}

strcpy(concatenated_string, first_string);
strcat(concatenated_string, second_string); //concatenate

printf("\nConcatenated string: %s\n", concatenated_string); //result

free(concatenated_string);

return 0;
}

You might also like