Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get size of char* x[]

Tags:

c++

How would I get the size of this:

 char* stringit[4] = {"H","H","UH","i"};

I tried:

sizeof(stringit);

and it outputed 32.

I tried to make a for loop:

for (i= 0; check != 0; ++i){
    check = stringit[i];
}

and that did not work either. Is there anyway to do this without having to pass in the size of the array?

like image 793
user1334858 Avatar asked Nov 20 '25 18:11

user1334858


2 Answers

make it a NULL terminated array of pointers

 char* stringit[] = {"H","H","UH","i" , NULL };

Then just count the pointers until you find a null pointer.

The right way to get the number of elements of an array is to divide its actual size (in bytes) by the size of an element:

sizeof(stringit) / sizeof(stringit[0])

But unless you have extremely specific requirements, you should use a standard container like vector (and string too instead of char* C strings):

std::vector<std::string> stringit = {"H","H","UH","i"};
std::cout << stringit.size();

As @KonradRudolph mentioned, vector is nice if your number of elements is variable. If the number of elements is known at compile time and will never change you could instead use array:

std::array<std::string, 4> stringit = {"H","H","UH","i"};
std::cout << stringit.size();
like image 43
syam Avatar answered Nov 22 '25 08:11

syam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!