print size of an array?

Oct 26, 2014 at 5:06pm
I have an array and in one function i need to print the size of it in megabytes

Is there a way to do so? I am not sure if sizeof prints the size of an array in megabytes

Right now in this function I have:
1
2
3
4
5
  void Entrylist::Size()
{
   cout << "Size of list: " << sizeof(entryList) << " mb.";
//entryList is my array of Entries
}
Last edited on Oct 26, 2014 at 5:10pm
Oct 26, 2014 at 5:08pm
sizeof gives the size in bytes.
Oct 26, 2014 at 5:08pm
so sizeof is the correct one to use?
Oct 26, 2014 at 5:13pm
Oct 26, 2014 at 5:13pm
//entryList is my array of Entries
sizeof would work corectly only if entryList is a static array. If it is a dinamic array (allocated by new) it would not give correct results.
In this case you need to multiply sizeof(Entry) by amount of entries.
This method does not take into account dynamic memory used by Entries if it is relevent to you.
Oct 26, 2014 at 5:15pm
Well, it depends... sizeof a pointer will give you the size of the pointer without caring about what the pointer points to.

1
2
3
4
char arr[5];
char* ptr = new char[5];
std::cout << sizeof(arr) << std::endl; // 5
std::cout << sizeof(ptr) << std::endl; // sizeof(char*) - usually 4 or 8 
Oct 26, 2014 at 5:20pm
if i did sizeof(entryList[2]) for example would that give me the size of the one Entry?

and yeah, the dynamic memory is important
Last edited on Oct 26, 2014 at 5:21pm
Oct 26, 2014 at 5:25pm
All entries in the array has the same size, the way sizeof computes the size. Note that sizeof is computed at compile time. It's only looking at the type when deciding the size. sizeof(entryList[2]) will give you the same value as sizeof(entryList[1]) and sizeof(entryList[0]).
Last edited on Oct 26, 2014 at 5:28pm
Topic archived. No new replies allowed.