c++ - 无法检索静态 char * 数组

标签 c++

我有以下代码片段,目的是获取特定项目列表并打印。它编译正常,但在运行时,输出不符合预期。我在结果出乎意料的地方添加了评论。请让我知道我在这里做错了什么。

#include <iostream>

using namespace std;

class cSample
{
private:
    static const char *list1[];
    static const char *list2[];

public:
    cSample();
    const char **GetList(int);
};

cSample::cSample()
{
}

const char *cSample::list1[] = {"Item1" , "Item2" , "Item3"};
const char *cSample::list2[] = {"Item4" ,"Item5" ,"Item6"};

const char **cSample::GetList(int i)
{
    switch(i)
    {
    case 1:
        return cSample::list1;
        break;
    case 2:
        return cSample::list2;
        break;
    default:
        break;
    }
}

int main(int argc , const char *argv[])
{
    cSample *oSample = new cSample();

    const char**list1Item = oSample->GetList(1);//Here getlist returns list1+list2 item which is wrong , I am not sure why...
    cout << "Items from List1 " << endl; 
    while(*list1Item != NULL)
    {
        cout << *list1Item << endl;
        list1Item++;
    }

    const char **list2Item = oSample->GetList(2);//whereas list2 items are returned correctly using same method any idea why?
    cout << "Items from list2" << endl;
    while(*list2Item != NULL)
    {
        cout << *list2Item << endl;
        list2Item++;
    }
    return 0;
}

最佳答案

您需要添加一个 NULL 来终止您的列表

const char *cSample::list1[] = {"Item1" , "Item2" , "Item3", NULL};

关于c++ - 无法检索静态 char * 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26292967/

相关文章:

C++ ulong到类方法指针并返回

c++ - 模板的实例化会导致二进制代码重复,编译器会阻止它吗?

c++ - 使用 g++ 编译主模块的奇怪错误

c++ - C++ 与 C 处于同一级别吗?

c++ - clang 不识别 protected 数据成员

C++ 结构引用类型

c++ - 在不调用 QThread::start() 的情况下使用 QThread 是否有意义?

c++ - Goto 无法正常工作 C++

c++ - 制作二维引擎 : compiling necessary libraries with the engine instead of the game

c++ - 使用范围 for 循环而不使用 auto 关键字 c++