C++查找 char* 数组中的元素数

C++ finding num of elements in a char* array

本文关键字:元素 数组 查找 char C++      更新时间:2023-10-16

有没有办法知道 char* 数组中的元素数?

我的代码是:

char* inputOptions[]={
    NULL,     
    "first sentence",
    "second sentence"}
for(int j=0;j<3;j++)
   cout<<inputOptions[j]<<endl;  

我想将"3"更改为依赖于"arr"的表达式。有没有办法这样做?

是的,你可以写

std::distance(std::begin(inputOptions), std::end(inputOptions));

在 C++03 中,使用

sizeof inputOptions / sizeof inputOptions[0]

但是,在 C++11 中,您最好使用以下范围访问数组:

for (auto option: inputOptions)
   cout << option << endl;
const char * inputOptions[] = {
    NULL,     
    "first sentence",
    "second sentence" };
const int numOptions = sizeof(inputOptions) / sizeof(inputOptions[0]);
您可以将

sizeof()与静态数组一起使用,它将为您提供以字节为单位的大小。如果将其除以指针大小,将得到数组的大小:

siz = sizeof(inputOptions)/sizeof(char*);