为什么sizeof Variablename/sizeof*VariableName不能按预期工作?

2 c++ sizeof

 class Simple {
      string *data ;
      //some functions and declaration of some variable,const, dest
 };
Run Code Online (Sandbox Code Playgroud)

我什么时候做的;

 data = new string [10] ;

 cout << sizeof data / sizeof *data << endl ;

 ==> 1 // output 


 data = new string [50];
 cout <<sizeof data / sizeof *data <<endl ;

==> 1 // output 

**Why** do all output display the same ?
Run Code Online (Sandbox Code Playgroud)

Bat*_*hyX 5

因为它根本不起作用.

它仅适用于以这种方式声明的普通旧数组:

 string a[10];
Run Code Online (Sandbox Code Playgroud)

这是这项工作的唯一案例.

在您的情况下,您无法从指针中检索大小.你必须存储你拥有的大小,或者只使用所有拥有.size()成员的STL容器.后者是优选的.