I'm working on a task to convert
void f(char s[], char t[]){
int k=0;
while (s[k]=t[k]) k++;
}
into the equivalent form of
void f(char *s, char *t)
{
while (____);
}
I know it can be converted to
void f(char *s, char *t){
int k=0;
while (*(s+k)=*(t+k))k++;
}
The problem is, it is only allowed to fill in the bracket. I am running out of idea
Simply increment the pointers themselves.
void f(char *dest, char *source) {
while ((*dest++ = *source++));
}
This will end the loop when the assigned character is NUL ('\0'
).
Example program, with type qualifier correctness:
#include <stdio.h>
void f(char *dest, const char *source) {
while ((*dest++ = *source++));
}
int main(void) {
char buffer[32];
const char *string = "Hello, world!";
f(buffer, string);
puts(buffer);
}
Of course, this has the same issues as the standard library strcpy
, you must be careful to make sure there is enough space in your destination buffer before calling this function.