0

I have the below piece of code and I'm very confused by it. I'm trying to figure out how much memory (bytes of memory/space is actually being taken up by my partially filled array). I've got the below piece of code but I'm a bit confused.

If I declare a string array of 8 elements, and partially fill the elements with the two strings. The for loop will start at 0 and go until size of my array 32 possible bytes (assuming I need 4 bytes per string) divided by size of the first element in the array. That is returns 4 - the size of the element of the first string in the array. But that still doesn't tell me how many letters/characters are in that string.

I understand inside the loop we increment count when the value in the array doesn't equal a blank/null value. Giving us the total filled (non empty) positions in our array. However I still don't have a value for our actual amount of characters.

How does this tell us how many characters are in my strings?

#include <iostream>
#include <string>
using namespace std;

int main() 
{
string test_array[8] = {"henry", "henry2"};
size_t count = 0;

for (size_t i = 0; i < sizeof(test_array)/sizeof(*test_array); i++) 
{

    cout << "NOT THE POINTER: "<<sizeof(test_array) << endl;
    cout << "POINTER: "<<sizeof(*test_array) << endl;

    if(test_array[i] != "")
        count ++;
}

int num_elem = sizeof(test_array)/sizeof(test_array[0]);
cout << num_elem << endl;
cout << count << endl;

return 0;
}

1 Answer 1

2

To know how many characters are in a std::string use the size() method.

Sign up to request clarification or add additional context in comments.

3 Comments

or the length() method.
But length() works on a particular item. I know I can say test_array[o].length(); but what if I don't know how many items are in my array (since its partially filled) and i want to be able to find out how many characters i have in total (in this example in the first two fields).
@YelizavetaYR This answer is proposing you change count++; to count += test_array[i].size();. count += test_array[i].length(); is just another option.

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.