patterncModerate
Pointer version of strcat
Viewed 0 times
versionpointerstrcat
Problem
Write a pointer version of the function
This is the version of
Here is my solution:
There are 2
The second loop will copy the elements of the string
The exercise can be found at page 121 in K&R second edition.
strcat that we showed in Chapter 2: strcat(s, t) copies the string t to the end of s.This is the version of
strcat from Chapter 2:void strcat(char s[], char t[]) {
int i, j;
i = j = 0;
while(s[i] != '\0') /* find the end of s */
i++;
while((s[i++] = t[j++]) != '\0') /* copy t */
;
}Here is my solution:
void custom_strcat(char *s, char *t) {
while(*s) /* finding the end of the string */
s++;
while((*s++ = *t++)) /* copy t */
;
}There are 2
while loops in my function, first loop will run until *s is equal to '\0'. At each iteration the value of s is incremented - thus, it will point to the next element;The second loop will copy the elements of the string
t at the and of s. The incrementation is done in the test part - even though after the loop stops s and t will point to other objects.This technique couldn't be applied in the first loop because when the loop stops s will point to an irrelevant value.The exercise can be found at page 121 in K&R second edition.
Solution
It looks idiomatic and bug-free.
Perhaps
Could have just a single pair of parentheses.
The signature of strcat is usually
This technique couldn't be applied in the first loop because when the loop stops s will point to an irrelevant value.
You could write that as,
s++;Perhaps
++s as a habit unless postfix s++ is required (as it is during the copy).while((*s++ = *t++))Could have just a single pair of parentheses.
void custom_strcat(char *s, char *t)The signature of strcat is usually
char strcat(char destination, const char* source). The const means that the source buffer is not modified. The return code is supposed to be a pointer to the original (unmodified) source value, so to implement this the implementation would need to increment a local variable copy of destination.This technique couldn't be applied in the first loop because when the loop stops s will point to an irrelevant value.
You could write that as,
if (s) while ((++s));.Code Snippets
while((*s++ = *t++))void custom_strcat(char *s, char *t)Context
StackExchange Code Review Q#40616, answer score: 10
Revisions (0)
No revisions yet.