Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a C function with prototype char* cat(char* s1, char* s2) that takes two n

ID: 3868266 • Letter: W

Question

Write a C function with prototype char* cat(char* s1, char* s2) that takes two null () terminated char arrays s1 and s2, allocates sufficient heap memory to store the concatenation of the two arrays (including a terminating null () character), copies the contents of arrays s1 and s2 into that newly allocated array (including the terminating null () character), then returns a pointer to the new char array. You may not use functions from the string.h library to accomplish the above tasks, in particular, you must manually determine the length of char arrays s1 and s2 by searching for their terminating null characters.

Explanation / Answer

#include <stdio.h>

#include <stdlib.h>

char* cat(char* s1, char* s2)

{

int i, j;

char *s3=malloc(50);

  

// copy the first string

for(i = 0; s1[i] != ''; ++i)

s3[i] = s1[i];

// copy the second string

for(j = 0; s2[j] != ''; ++j, ++i)

{   

s3[i] = s2[j];

}

s3[i]='';

// return the new string after copy

return (s3);

}

int main(int argc, char** argv) {

char input1[]="hello";

char input2[]="World";

char *new_string;

printf("String1 :%s",input1);

printf(" String 2:%s",input2);

new_string = cat(input1, input2);

printf("After concatenation :%s",new_string);

return (EXIT_SUCCESS);

}

sample output:

String1 :hello

String2 :World

After concatenation :helloWorld

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote