1

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?

3 Answers 3

5

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;
Sign up to request clarification or add additional context in comments.

Comments

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

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

2 Comments

Because dynamic arrays are just pointers - the compiler can not know at compile-time how much memory will be allocated to a pointer at run-time.
The denominator should be sizeof(inputOptions[0]) rather than hard-coded for char*. Doing it that way costs nothing, and makes the code more robust against type changes.
1

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*);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.