sizeof continues to return 4 instead of actual size

前端 未结 5 1155
孤街浪徒
孤街浪徒 2020-12-21 04:07
#include 

using namespace std;

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


        
5条回答
  •  星月不相逢
    2020-12-21 04:16

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

提交回复
热议问题