So I have come up with the following method, since it's within the scope of what I have learned so far from my book. I am getting some strange output though.
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];
void link_array(char first[], char second[], long size);
int my_string_length(char string[]);
void concat(char c_string1[], char c_string2[], long ssize);
long totalsize = 0;
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);
totalsize = totalsize + my_string_length(string1) + my_string_length(string2);
link_array(string1, string2, totalsize);
concat(string1, string2, totalsize);
return 0;
}
void link_array(char first[], char second[], long size)
{
char *c;
c = malloc(size + 1);
if (c == NULL)
{
puts("Memory allocation failed");
exit(1);
}
printf("You allocated %lu bytes of memory to store the string\n", size + 1);
}
void concat(char c_string1[], char c_string2[], long ssize)
{
char stringout[ssize + 1];
int ctr = 0;
int ctr2= 0;
/* concatenate the two strings */
while(c_string1[ctr] != '\0' && c_string1[ctr] != '\n')
{
stringout[ctr] = c_string1[ctr];
ctr++;
}
/* insert a space between the strings */
ctr++;
stringout[ctr] = ' ';
while(c_string2[ctr2] != '\0' && c_string2[ctr2] != '\n')
{
stringout[ctr] = c_string2[ctr2];
ctr++;
ctr2++;
}
/* add null character to end of string */
ctr++;
stringout[ctr] = '\0';
printf("%s\n", stringout);
}
int my_string_length(char string[])
{
int ctr = 0;
while(string[ctr] != '\0') {
ctr++;
}
printf("length %d\n", ctr - 1);
return ctr - 1;
}
It seems to concatenate the strings together but not well, and I am getting some odd characters after the output as well as for spaces within the output.
Code:
Enter your first line of text (maximum 80 characters):
Testing with
Enter your second line of text (maximum 80 characters):
letters
Actual output:
length 13
length 7
You allocated 21 bytes of memory to store the string
Testing with
And if I put numbers in the input I get this:
Code:
Enter your first line of text (maximum 80 characters):
12345
Enter your second line of text (maximum 80 characters):
67890
Actual output:
length 5
length 5
You allocated 11 bytes of memory to store the string
1234567890??
Any ideas why it sort of works?