0

I am trying to figure out how much my structure will take memory consumption.Consider the following code

   struct tNode{
       short data;
       tnode *left;
       tnode *right;
       tnode *student;    
 }

so i know data is 2 bytes but what about *left ,*right and *student ,how much memory will they consume and how to calculate it.

1 Answers1

1

You're looking for the sizeof operator

Returns size in bytes of the object representation of type

Example usage:

#include <iostream>

class tnode;

struct tNode {
       short data;
       tnode *left;
       tnode *right;
       tnode *student;
};

int main()
{

  std::cout << sizeof(tNode) << std::endl;
  return 0;
}

Output on my machine:

32
Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93
  • but my computer is outputting 16 bytes –  Mar 17 '19 at 13:32
  • 1
    @newprogrammer the output is implementation dependent – Aykhan Hagverdili Mar 17 '19 at 13:34
  • 2
    @newprogrammer In C++, not every type is restricted to have a fixed size. They differ on different implementations. – L. F. Mar 17 '19 at 13:35
  • @newprogrammer then your machine is probably using 32bit pointers while Ayxan's is using 64bit pointers. – Jesper Juhl Mar 17 '19 at 13:36
  • 2
    @newprogrammer The compiler adjusts the size of the struct for performance reasons. More specifically, it pads bytes between members of the struct to ensure alignment of the members. More information here: https://en.cppreference.com/w/c/language/object – Yashas Mar 17 '19 at 13:40