C++ 如何使用strlen()获取数组的长度?

C++ 如何使用strlen()获取数组的长度?,c++,C++,我不明白为什么不能使用strlen()获取数组的长度。如何调试它 main.cpp是: char* vector_1 = q2_input_source(); function.cpp是: char* q2_input_source() { static char* source = new char[10]; int index = 0; cout << "enter (ESC) to escape the source-char-program!" &

我不明白为什么不能使用strlen()获取数组的长度。如何调试它

main.cpp是:

char* vector_1 = q2_input_source();
function.cpp是:

char* q2_input_source() {
    static char* source = new char[10];

    int index = 0;
    cout << "enter (ESC) to escape the source-char-program!" << endl;


    while (_getch() != 27)
    {
        cout << "Input your source_char " << index << " elment: " << endl;
        cin >> source[index];
        index = index + 1;
        cout << endl;
    }
    int length = strlen(source);
    cout << length << endl;


    return source;

}
char*q2_输入_源(){
静态字符*源=新字符[10];
int指数=0;
cout
while(_getch()!=27&&index<9)
{

这个问题被标记为C++,C++中的标准方法是用STD::string来表示它们自己的长度。不要把字符与char *混淆。它只是太多的麻烦和太多的错误。简短的回答-没有返回C数组长度的函数。<代码>斯特伦< /代码>是F。函数,它接收一个
char
数组,并在数组中搜索
0
值,与数组长度的任何关系都是巧合
这样会丢弃读取的字符,因此后续的
cin>
不会传递所有数据。第二个问题是数组不会以null结尾,除非以null结尾,否则不会以null结尾。
    while (_getch() != 27 && index < 9)
    {
        cout << "Input your source_char " << index << " elment: " << endl;
        cin >> source[index];
        index = index + 1;
        cout << endl;
    }
    source[index] = '\0';  // You need to add a string terminator.
    int length = strlen(source);