Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
895 views
in Technique[技术] by (71.8m points)

c++ - sizeof continues to return 4 instead of actual size

#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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...