K&R code example confusion: copy string
edit: fixed copy, sorry about the typo.
In chapter one, the K&R introduces a function copy as follows:
void copy(char to[], char from[]) {
/* copy from from[] to to[], assumes sufficient space */
int i = 0;
while ((to[i] = from[i]) != '\0') {
i++;
}
}
Tinkering around a little with this function, I had some unexpected
results. Example program:
int main() {
char a[3] = {'h', 'a', '\n'};
char b[3];
printf("a: %s", a); // prints ha
copy(b, a);
printf("a: %s", a); // prints nothing
printf("b: %s", b); // prints ha
return 0;
}
Now to my questions:
Why does the copying from a to b work, that is why does the while loop in
copy ever terminate even though a does not contain a '\0'?
Why is a mutated?
Thanks!
No comments:
Post a Comment