sizeof继续返回4而不是实际大小 [英] sizeof continues to return 4 instead of actual size

查看:148
本文介绍了sizeof继续返回4而不是实际大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

感谢您的时间。

推荐答案

sizeof 返回表达式的大小。对你来说,这是一个 std :: string ,对于你的实现 std :: string ,这是四。 (可能是指向缓冲区的指针,内部。)

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

但是你看到,缓冲区只是由字符串指向,它不影响 std :: string 本身。你需要 message.size(),它给出了缓冲区指针指向的字符串的大小。

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.

随着 string 的内容改变,缓冲区指针指向的变化,但指针本身总是相同的大小。

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

请考虑以下事项:

struct foo
{
    int bar;
};



此时, sizeof(foo)是已知的;它是一个编译时常量。它是 int 的大小,以及任何其他填充编译器可能会添加。

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.

您可以让 bar 接受任何您想要的值,因为 bar 的值与 bar 本身的类型和大小没有关系。

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.

这篇关于sizeof继续返回4而不是实际大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆