Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sizeof continues to return 4 instead of actual size

Tags:

c++

sizeof

#include <iostream>

using namespace std;

int main()
{
    cout << "Do you need to encrypt or decrypt?" << endl;
    string message;
    getline(cin, message);

    int letter2number;

    for (int place = 1; place < sizeof(message); place++)
    {
        letter2number = static_cast<int>(message[place]);
        cout << letter2number << endl;
    }
}

Examples of problem: I type fifteen letters but only four integers are printed. I type seven letters but only four integers are printed.

The loop only occurs four times on my computer, not the number of characters in the string.

This is the only problem I am having with it, so if you see other errors, please don't tell me. (It is more fun that way.)

Thank you for your time.

like image 982
Guest Avatar asked Dec 03 '22 13:12

Guest


2 Answers

sizeof returns the size of an expression. For you, that's a std::string and for your implementation of std::string, that's four. (Probably a pointer to the buffer, internally.)

But you see, that buffer is only pointed to by the string, it has no effect on the size of the std::string itself. You want message.size() for that, which gives you the size of the string being pointed to by that buffer pointer.

As the string's contents change, what that buffer pointer points to changes, but the pointer itself is always the same size.


Consider the following:

struct foo
{
    int bar;
};

At this point, sizeof(foo) is known; it's a compile-time constant. It's the size of an int along with any additional padding the compiler might add.

You can let bar take on any value you want, and the size stays the same because what bar's value is has nothing to do with the type and size of bar itself.

like image 165
GManNickG Avatar answered Dec 23 '22 19:12

GManNickG


You want to use message.size() not sizeof(message).

sizeof just gives the number of bytes in the data type or expression. You want the number of characters stored in the string which is given by calling size()

Also indexing starts at 0, notice I changed from 1 to 0 below.

for (int place = 0; place < message.size(); place++)
{
    letter2number = static_cast<int>(message[place]);
    cout << letter2number << endl;
}

Any pointer on an x86 system is only 4 bytes. Even if it is pointing to the first element of an array on the heap which contains 100 elements.

Example:

char * p = new char[5000];
assert(sizeof(p) == 4);

Wrapping p in a class or struct will give you the same result assuming no padding.

like image 40
Brian R. Bondy Avatar answered Dec 23 '22 21:12

Brian R. Bondy