I understand that s
and t
are both pointers and they are being copied to one another but the incrementing part is confusing to me.
void funct(char *s, char *t){
while( *s++ = *t++ );
}
I understand that s
and t
are both pointers and they are being copied to one another but the incrementing part is confusing to me.
void funct(char *s, char *t){
while( *s++ = *t++ );
}
The function performs a copy of the string the first character of which is pointed to by the pointer t
into a character array pointed to by the pointer s
using the pointers.
void funct(char *s, char *t){ while( *s++ = *t++ ); }
To make it more clear you can rewrite the while loop the following way
void funct(char *s, char *t)
{
while( ( *s = *t ) != '\0' )
{
s++;
t++;
}
}
The only difference is that the increment of the pointers in the last while loop is performed in the body of the while loop if the copied character is not the terminating zero character '\0' of the string pointed to by the pointer t.
That is characters pointed to by the pointer t
are assigned to characters pointed to by the pointer s. If the current copied character is equal to the terminating zero character then the condition of the loop evaluates to false. As a result one string is copied in another character array.
answer was here How does "while(*s++ = *t++)" copy a string? It is equivalent to this:
while (*t) {
*s = *t;
s++;
t++;
}
*s = *t;
When the char that t points to is '\0', the while loop will terminate. Until then, it will copy the char that t is pointing to to the char that s is pointing to, then increment s and t to point to the next char in their arrays.