This is a language-lawyer question.
The description of strcpy function is given at 7.24.2.3(p2):
The
strcpyfunction copies the string pointed to by s2 (including the terminating null character) into the array pointed to by s1.
So consider the following code:
char test[8] = "123";
strcpy(test + 3, "4567");
printf("%s\n", test); //1234567
It works as expected, but I'm confused about the object pointed to by test + 3. It is clear that object pointed to by test has declared type char[8]. But as far as I can see the Standard does not explicitly defined sort of this:
"If we have an array of n elements than a pointer to i < nth element can be considered a pointer to the first element of an array of n - i elements".
Since the function strcpy requires its first operand to be an array can we pedantically speaking apply pointer arithmetic as I showed above?
Of course s1 does not point to an array, it points to a char. But the term usage comes from the 7.1.4p1:
[...] If a function argument is described as being an array, the pointer actually passed to the function shall have a value such that all address computations and accesses to objects (that would be valid if the pointer did point to the first element of such an array) are in fact valid. [...]
For strcpy(test + 3, "4567"); the accesses test[3 + 0 ... 4] shall be valid, which is the case, among others possibilities, if test is an array of at least 8 characters.
Yes, because even though the semantics of the function strcpy only make sense when dealing with arrays instead of pointers, there is no way for strcpy (or any other function) to tell whether it was passed an array or a pointer to an array, since when an array is passed as an argument to a function, it decays to a pointer to its first element.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With