2

The book C++ Primer states the following:

Because arrays are passed as pointers, functions ordinarily don't know the size of the array they are given. They must rely on additional information provided by the caller.

The options described include using an end marker character, using a pointer to the position one pas the last element of the array, or using a parameter to represent the size of the array.

However, when I create a non-null terminated array of const char and pass that to a function called print, the << operator knows perfectly when to stop reading without any of these techniques. How does it know?

#include <iostream>

void print(const char line[]) {
    std::cout << line << '\n';
    return;
}

int main() {
    const char str[] {'f', 'o', 'o', ' ', 'b', 'a', 'r'};
    print(str);
    return 0;
}
L.S. Roth
  • 447
  • 2
  • 14
  • 1
    Just because it "works" once doesn't prove anything. Try for example to make `str[]` 8-char long, and add two more 8-char long strings `str1[]`, `str2[]` next to it, then see what prints for each of them. – dxiv Aug 16 '20 at 07:59
  • 1
    Alright, the output of that looked pretty horrible. Thanks for the example! – L.S. Roth Aug 16 '20 at 09:36
  • It doesn't "know perfectly when to stop". It's just bad luck that it happens to do what you expect. It could also write a bunch of junk after your text, and in that case, you'd be much more likely see the problem. – Pete Becker Aug 16 '20 at 15:59

2 Answers2

3

You just got lucky with the memory layout and had an accidental null-terminator.

On VS2019 I get an output of:

foo bar╠╠╠╠╠CÌ╦À<³3☺33Ò

Try popping in:

std::cout << sizeof(line) << '\n';

and

std::cout << sizeof(str) << '\n';

and you'll see the difference between the pointer size and the array size.

Further explanation:

When sizeof is applied to an array whose definition is visible to the compiler, it returns the number of bytes allocated to the array.

When sizeof is applied to any other array, the compiler cannot determine the size of the array and so can only give the size of the pointer to the array.

See: How to find the 'sizeof' (a pointer pointing to an array)?

Jasper Kent
  • 3,546
  • 15
  • 21
2

Actually, it is just undefined behave, that memory next to str has null termination, so in some cases print() function could print garbage

Midren
  • 409
  • 2
  • 7