Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
265 views
in Technique[技术] by (71.8m points)

c++ sizeof(array) return twice the array's declared length

I have a section of code in which two array are declared with sizes of 6 and 13, but when 'sizeof()' is used the lengths are returned as 12 and 26.

#include <iostream>
using namespace std;

int main(){

    enum charRaces {DWARF,ELF,GNOME,HALFELF,HALFLING,HUMAN};
    enum classes{WARRIOR,FIGHTER,RANGER,PALADIN,WIZARD,MAGE,ILLUSIONIST,PRIEST,CLERIC,DRUID,ROGUE,THEIF,BARD};

    short int races[6] = {DWARF,ELF,GNOME,HALFELF,HALFLING,HUMAN};
    short int classes[13] = {WARRIOR,FIGHTER,RANGER,PALADIN,WIZARD,MAGE,ILLUSIONIST,PRIEST,CLERIC,DRUID,ROGUE,THEIF,BARD};

    cout << "sizeof(races)"  << sizeof(races) << endl;
    cout << "sizeof(classes)"  << sizeof(classes) << endl;

    system("pause");

    return(0);
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

sizeof returns the size of a variable (in this case, your arrays), where sizeof(char) is 1. Since a char is one byte wide, sizeof returns the size of the variable in bytes. Since each short int is two bytes wide on your system, an array of 6 of them will have size 12, and an array of 13 will have size 26.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...