我试图计算一个char数组中的内容,直到null终止,但每次我编译我得到一个大于我的数组的数字

问题描述 投票:0回答:2

无论我为数组的大小设置什么值,我写的函数返回的值都要大一些。

我尝试过(* str ++)并从while循环中删除str ++,而不是现在的那些。

我正在使用Visual Studio 2019。

int strlen(char* str)
{
    int i = 0;

    while (*str != '\0')
    {
        i++;
        str++;

    }

    return i;
}

int main()
{
    char line[1];
    char* v = line;
    char* s = new char[1];
    cout << "for s " << strlen(s) << endl;
    cout << "for v " << strlen(v) << endl;

}
c++ pointers memory-management pointer-arithmetic
2个回答
3
投票

你忽略了null终止你的字符串。您的函数正在遍历数组的末尾并导致未定义的行为。一些字符串操作函数会将null放在最后,但是如果您希望字符串的终结为null,则必须自己将其放在那里。

char line[2];
char* v = line;
line[0]='x';
line[1]= '\0';

2
投票

数组的内容未定义。您没有使用任何字符填充任何数组,更不用说任何空终止符。在未正确空终止的字符数组上调用strlen()是未定义的行为。

© www.soinside.com 2019 - 2024. All rights reserved.