c++ sizeof( string )

后端 未结 8 1548
陌清茗
陌清茗 2020-12-09 13:59
#include 
#include 

int main(int argc, char *argv[])
{
   cout << "size of String " << sizeof( string );
               


        
8条回答
  •  余生分开走
    2020-12-09 14:42

    When string is defined as:

    char *string;
    

    sizeof(string) tells you the size of the pointer. 4 bytes (You're on a 32-bit machine.) You've allocated no memory yet to hold text. You want a 10-char string? string = malloc(10); Now string points to a 10-byte buffer you can put characters in.

    sizeof(*string) will be 1. The size of what string is pointing to, a char.

    If you instead did

    char string[10];
    

    sizeof(string) would be 10. It's a 10-char array. sizeof(*string) would be 1 still.

    It'd be worth looking up and understanding the __countof macro.

    Update: oh, yeah, NOW include the headers :) 'string' is a class whose instances take up 4 bytes, that's all that means. Those 4 bytes could point to something far more useful, such as a memory area holding more than 4 characters.

    You can do things like:

    string s = "12345";
    cout << "length of String " << s.length();
    

提交回复
热议问题