In: Computer Science
C
Implement the function Append (char** s1, char** s2) that appends the second character array to the first, replaces the first array with the result and replaces the second character array with the original first array. For example, if the first character array is "hello" and the second is "world" at the end of the function the new value of the first character array should be"helloworld" and the second array should be "hello". If the input is invalid the function should return 1. Otherwise, the function should return 0.
Input is double pointer (**). No use of <string.h>, USE malloc
#include <stdlib.h>
#include <stdio.h>
int
Append(char **s1, char **s2){
//implement
}
int main(){
char myArray1[7] = "hello";
char myArray2[10] = "world";
char *myArray3 = myArray1;
char *myArray4 = myArray2;
Append(&myArray3, &myArray4);
return 0;
}
Description:
Complete program which appends the second array to first array and assign first array to second array. To achieve the goal, memory is allocated first which can hold the appended array and another memory is allocated for holding first array. After allocating the memory, first the s1 is copied into newly allocated memory and then second array is concatenated/appended. null character '\0' inserted at the end of the result string.
Now s1 is copied into the another allocated memory tempS2. null character '\0' inserted at the end of the result string.
Now we can assign s1 and s2 the new values.
Complete program which you can copy:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int Append(char **s1, char **s2) {
/* get the length of the strings as will be needed
in allocating memory for new strings*/
int s1Length = strlen(*s1);
int s2Length = strlen(*s2);
char *tempS2 = NULL, *tempS1 = NULL;
/* return 1 if s1 or s2 string is null */
if (*s1 == NULL && *s2 == NULL) {
return 1;
}
/* Allocate memory which can hold concatenated string */
tempS1 = (char*)malloc(s1Length + s2Length + 1);
if (tempS1) {
/* copy first array s1 first and then concatenate second array s2
*/
strcpy(tempS1, *s1);
strcat(tempS1, *s2);
/* insert null charcter at end of the string */
tempS1[s1Length + s2Length] = '\0';
}
/* Allocate memory which can hold concatenated string */
tempS2 = (char*)malloc(s1Length + 1);
if (tempS2) {
/* copy first array s1 to placeholder for s2 */
strcpy(tempS2, *s1);
/* insert null charcter at end of the string */
tempS2[s1Length] = '\0';
}
/* assign tempS1 to s1 (concatenated string) and tempS2 to s2
(s1 value)*/
*s1 = tempS1;
*s2 = tempS2;
return 0;
}
int main() {
char myArray1[7] = "hello";
char myArray2[10] = "world";
char *myArray3 = myArray1;
char *myArray4 = myArray2;
Append(&myArray3, &myArray4);
printf("myArray3: %s\n", myArray3);
printf("myArray4: %s", myArray4);
return 0;
}
Formatted program:
Sample output: