简体   繁体   中英

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

is there a way to know num of elements in a char* array?

my code is :

char* inputOptions[]={
    NULL,     
    "first sentence",
    "second sentence"}

for(int j=0;j<3;j++)
   cout<<inputOptions[j]<<endl;  

and I would like to change '3' to some expression that depends on 'arr'. Is there a way to do so?

Yes, you can write

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

In C++03, use

sizeof inputOptions / sizeof inputOptions[0]

However, in C++11 you would do better to access the array using range for:

for (auto option: inputOptions)
   cout << option << endl;
const char * inputOptions[] = {
    NULL,     
    "first sentence",
    "second sentence" };

const int numOptions = sizeof(inputOptions) / sizeof(inputOptions[0]);

You can use sizeof() with static arrays, it will give you the size in bytes. If you divide that by the pointer size, you will get the size of the array:

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

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