为什么以下代码需要指针初始化?

时间:2015-10-23 18:32:48

标签: pointers const

当我在没有指针的情况下初始化以下数组时,我收到以下错误消息:

  

错误:char数组初始值设定项中的多余元素

为什么我需要用指针初始化这个数组?

const char MONTH_NAME[] ={"Jan", "Feb", "Mar", "Apr", "May", "Jun", 
 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
#include <iostream>
using namespace std;

 const char* MONTH_NAME[] ={"Jan", "Feb", "Mar", "Apr", "May", "Jun", 
 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};

const char* GetOldMonthName(int month){
    if(1 <= month && month <= 12){
        return MONTH_NAME[month - 1];
    }
    return 0;
}

int main(){
    int month;

    cout << "Enter the month number." <<endl;
    cin  >> month;
    const char* name = GetOldMonthName(month);

    if(name == 0){
        cout << "That is not month." <<endl;
    }
    else{
        cout <<"The number is " << name << endl;
    }

    return 0;
}

1 个答案:

答案 0 :(得分:0)

以这种“非指针”形式:

const char MONTH_NAME[] ={"Jan", "Feb", "Mar", "Apr", "May", "Jun", 
 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};

MONTH_NAME被声明为 const char 数组。 const char的数组(由'\0'终止时)也称为C样式字符串。但是您尝试使用“const char数组”(即字符串数组)初始化此字符串。因此,错误。

例如,初始化数组的第一个元素是"Jan",它本身是一个const char(一个字符串)的数组。

在另一种“指针”形式中:

const char* MONTH_NAME[] ={"Jan", "Feb", "Mar", "Apr", "May", "Jun", 
 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};

MONTH_NAME被声明为指向const char 的指针数组,它由代码中的const字符串列表正确初始化。因此,没有错误。