Mr.*_*ava -2 c++ arrays size pointers char
void printsize(const char arr[]){
cout<<"size is: "<<strlen(arr)<<endl;
}
main(){
char a[7] = {'a', 'b', 'c','d', 'c', 'b', 'a'};
printsize(a)
return 0
}
Run Code Online (Sandbox Code Playgroud)
它将输出以下内容:size为11
数组不存在11。为了使函数输出正确的大小(7),我应该怎么做?我不想设置for循环。
你不能 仅仅从中const char arr[],它将如何知道数组的大小?解决方法可能是具有哨兵值。在的情况下strlen,该哨兵值'\0'在字符串的末尾。将其添加到您的数组:
char a[8] = { 'a', 'b', 'c','d', 'c', 'b', 'a', '\0' };
Run Code Online (Sandbox Code Playgroud)
另外,a该函数中不存在,您可能打算使用arr:
std::cout << "size is: " << strlen(arr) << std::endl;
Run Code Online (Sandbox Code Playgroud)
这给您预期的输出7。另外,您应该始终将main函数声明为int main。int不建议使用隐式且非标准的隐式,并非所有编译器都支持隐式。
的先决条件strlen是参数指向以空值结尾的数组(字符串)。您的数组不是以空值结尾的,因此您通过将该数组(指向)传递到中来违反该前提条件strlen。
违反标准功能前提条件的程序的行为是不确定的。
如何在C ++中使用函数返回char数组的大小?
您可以使用模板获取数组的大小:
template <class T, std::size_t N>
std::size_t
size(const T (&array)[N])
{
return N;
}
Run Code Online (Sandbox Code Playgroud)
用法:
char a[7] = {'a', 'b', 'c','d', 'c', 'b', 'a'};
cout<<"size is: "<<size(a)<<endl;
Run Code Online (Sandbox Code Playgroud)
请注意,您不需要自己编写此模板,因为标准库已经为您提供了它。它被称为std::size(在C ++ 17中引入)。