c ++ sizeof(array)返回数组的声明长度的两倍 [英] c++ sizeof(array) return twice the array's declared length

查看:258
本文介绍了c ++ sizeof(array)返回数组的声明长度的两倍的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一段代码,其中两个数组声明为大小6和13,但是当使用'sizeof()'时,长度返回为12和26.

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)\t"  << sizeof(races) << endl;
    cout << "sizeof(classes)\t"  << sizeof(classes) << endl;

    system("pause");

    return(0);
}


推荐答案

sizeof 返回变量的大小(在本例中为您的数组),其中 sizeof(char)为1.由于 char 为一个字节宽, sizeof 返回变量的大小(以字节为单位)。由于每个 short int 在您的系统上有两个字节宽,所以其中6个数组的大小为12,而13个数组的大小为26。

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.

这篇关于c ++ sizeof(array)返回数组的声明长度的两倍的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆