我有以下代码片段,目的是获取某些项目列表并打印。它可以正常编译,但是在运行时,输出不符合预期。我在结果意外的地方添加了评论。请让我知道我在做什么错。
#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/