I am trying to concatenate two strings together into a third string array, and allocating memory to store the third string and return the pointer to it.
Here is what I have so far.
Code:/* concatenate two strings and malloc() memory to store a third strings */ #include <stdio.h> #include <stdlib.h> #define MAX 81 char string1[MAX], string2[MAX]; char link_array(char first[], char second[], int length); int main() { /* string input */ puts("Enter your first line of text (maximum 80 characters): "); fgets(string1, sizeof(string1), stdin); puts("Enter your second line of text (maximum 80 characters): "); fgets(string2, sizeof(string2), stdin); printf("You entered %s", link_array(string1, string2, MAX)); return 0; } char link_array(char first[], char second[], int length) { char *end1, *end2, c; int ctr; long totalsize; end1 = first; /* get memory address of last character in first string */ for (ctr = 0; ctr < length; ctr++) { while(first[ctr] != '\0') end1 = &first[ctr]; } end2 = second; /* get memory address of last character in second string */ for (ctr = 0; ctr < length; ctr++) { while(second[ctr] != '\0') end2 = &second[ctr]; } /* malloc() the amount of memory needed to store string1 and string2 combined */ totalsize = (&end1 - &first) + (&end2 - &second); c = malloc(totalsize + 1); if (c == NULL) { puts("Memory allocation failed"); exit(1); } /* combine the two strings using the memory addresses stored in end1 and end2 */ /* can't figure this part out */ return c; }



LinkBack URL
About LinkBacks




