简体   繁体   中英

How does the output operator know the size of an array of chars?

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;
}

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)?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM