I need to write a program that concatenates two strings in to the first string. I can't use a third parameter to hold the new string. When I run the program I get no output, so I'm pretty sure the problem is in my function that concatenates the two strings.
#include <stdio.h>
#define MAX_SZ 81
int concatString(char s1[], char s2[]); // concatenates s2 onto s1, returns length of s1
int getString(char c[], int len);
main(void)
{
char array1[MAX_SZ * 2];
char array2[MAX_SZ];
int string1 = 0;
int string2 = 0;
int concat = 0;
printf("Please String # 1 up to 80 characters long:\n");
string1 = getString(array1, MAX_SZ);
printf("Please enter String #2 up to 80 characters long:\n");
string2 = getString(array2, MAX_SZ);
concat = concatString(array1, array2);
printf("You entered \"%s\" (length = %i)\n", array1, concat);
return 0;
}
int getString(char c[], int len)
{
int i = 0;
char d = 0;
while (d != '\n' && i < len)
{
d = getchar();
c[i++] = d;
}
c[--i] = '\0';
return (i);
}
int concatString(char s1[], char s2[])
{
int i, j;
for (i = 0; s1 != '\0'; ++i)
s1[i] = s1[i];
for (j = i; s2 != '\0'; ++j)
s1[j] = s2[j];
s1 [i + j] = '\0';
return (i + j);
}
s1 != '\0'does not mean what you think it means. It looks like you wants1[i] != '\0'. Similarly with s2.i, should be a big red flag. The difference is that yours compares the pointers1with '\0' whereas mine compares one of the characters in the array to whichs1points.s1is a pointer to achar,s1[i]is a character in your string.