#include <stdio.h>
void strpcat(char *s, char *t) {
int i = 0;
while (*s++ != '\0')
i++;
while ((*(s+i) = *t++) != '\0')
i++;
}
int main(void) {
char a[20] = "Hello";
char b[] = "Bye";
strpcat(a, b);
printf("%s\n", a);
return 0;
}
I wanted to write rewrite the strcat() function with pointers, but when I run the program nothing changes.
Nothing affects to a array, what did I do wrong?
The one problem is this while loop
If
*stris equal to'\0'nevertheless the pointersis incremented. So the original string will not be changed. At least the second string will be appended to the array after the source string.Another problem is using the variable
iin the second while loopbecause the pointer
swas already incremented in the previous while loop. Using the incremented variableiand the incremented pointersthe pointer expressions + iwill have an incorrect address.The variable
iis redundant.The function can be declared and defined the following way
and called like
Pay attention to that the second parameter should be declared with the qualifier
constbecause the second passed string is not changed within the function. Also you could add the qualifierrestrictas in the standard functionstrcat