Skip to content

Commit fa219d9

Browse files
committed
revise answer
Added a check for NULL pointers and did other minor tweaks.
1 parent 26b614f commit fa219d9

File tree

1 file changed

+9
-7
lines changed

1 file changed

+9
-7
lines changed

chapter05/5-3.c

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
/*
22
* Exercise 5-3. Write a pointer version of the function strcat that we showed
33
* in Chapter 2: strcat(s,t) copies the string t to the end of s.
4+
*
45
* By Faisal Saadatmand
56
*/
67

@@ -12,18 +13,19 @@ void strCat(char *, char *);
1213
/* concatenate t to end of s; s must be big enough */
1314
void strCat(char *s, char *t)
1415
{
15-
while (*s) /* find end of s */
16+
while (s && *s) /* find end of s */
1617
++s;
17-
while ((*s++ = *t++)) /* copy t */
18+
while (s && t && (*s++ = *t++)) /* copy t */
1819
;
1920
}
2021

2122
int main(void)
2223
{
23-
char string1[64] = { "test this " };
24-
char string2[] = { "function" };
24+
char str1[64] = { "conca" };
25+
char str2[] = { "tonate" };
2526

26-
strCat(string1, string2);
27-
printf("%s\n", string1);
28-
return 0;
27+
strCat(str1, str2);
28+
printf("%s\n", str1);
29+
30+
return 0;
2931
}

0 commit comments

Comments
 (0)