mercredi 29 juin 2016

Why is sizeof (class with character variable) anomalous in C++? [duplicate]

This question already has an answer here:

Consider the following code:

#include <iostream>
#include <conio.h>> 
using namespace std;

class book 
{ 
    char Title;
    int no_of_pages; 
public: 
    void read(); 
    void show(); 
}; 

int main()
{
    book ob;
    char Title;
    cout << sizeof(book) << " " << sizeof(Title) << endl;

    getch();
    return 0;
}

The output of the code is

8 1

If I change the definition of 'Title' in the class to following:

char Title[5];

and the main() 'Title' to

char Title[5];

the output changes to:

12 5

To see if this is something which is done to all string variables in the program, I used the 'Title' in main(). But, the pattern is apparent for a string declared in a class.

For the sake of completion, the pattern is :

Size of character array is taken to be the least multiple of 4 greater than the actual size of array

Question: Although I understand it is implementation dependent, does anyone know or can suggest a reason for this behaviour of C++ 11?

My compiler is VS 2012, for 64-bit Windows.

Aucun commentaire:

Enregistrer un commentaire