2
 class Simple {
      string *data ;
      //some functions and declaration of some variable,const, dest
 };

When I did ;

 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 ?
  • 1
    possible duplicate of [C -> sizeof string is always 8...](http://stackoverflow.com/questions/4941142/c-sizeof-string-is-always-8) – Johan Kotlinski Feb 10 '11 at 12:42

3 Answers3

5

Because it simply doesn't work at all.

It only works for plain old arrays that are declared this way :

 string a[10];

and it is the only case when this work.

in your case, you can't retrieve the size from the pointers you have. you have to either store the size of what you have, or just use the STL containers which all have a .size() member. The latter is preferable.

BatchyX
  • 4,986
  • 2
  • 18
  • 17
3

Because sizeof is a compile-time calculation, not a run-time one. And your array size is not known until run-time.

sizeof does not know anything about where the pointer points to, so it doesn't matter how big of a buffer you allocated, or even that you allocated a buffer at all. You can even do:

data = NULL;
x = sizeof(*data);

Because it's calculated at compile-time, there is no null-pointer dereferencing.

sizeof only looks at the datatype you pass in, not the data itself. In this case, string*, which is the same size no matter where it points to.

You have a few options to make this "work":

  1. Use a statically-sized array (e.g. string data[50];) where you can use your sizeof idiom, but of course you get all the standard limitations of static arrays then.
  2. Continue to dynamically allocate using new, but just store the array size and pass it around wherever you need it.
  3. Preferred: Use std::vector for arrays -- this is basically the best of all worlds.
tenfour
  • 36,141
  • 15
  • 83
  • 142
2

What is sizeof data? It is the size of a string*. What is sizeof *data? It is the size of what data points to, that is, size of string. Both of these are constant.

data does not have any knowledge about how many elements you allocated - it is just a stupid pointer.

You have to remember, sizeof always evaluates in compile-time. So you can never get sizeof info about things that happens in run-time, like new calls.

Johan Kotlinski
  • 25,185
  • 9
  • 78
  • 101