1

我正在尝试将 c 字符串向量转换为 c 字符串数组。我试过这个,但它似乎不能正常工作:

int glfxGetProgramList(int effect, char** progList, int* count)
{
    std::vector<char*> list;
    gEffects[effect]->GetProgramList(list);
    fprintf(stderr, "Lib Output: %s\n", list[0]);
    progList = &list[0];
    int size = list.size();
    memcpy(count, &size, sizeof(int));
}

从 stderr 返回的调试输出在函数内部是正确的。但是,当我在项目中使用此函数并尝试输出列表中的第一项时,它会因分段错误而崩溃。这是我项目中的代码:

char ** list;
int size;
glfxGetProgramList(effect, list, &size );
fprintf(stderr, "Output: %s\n", list[0]);

知道我做错了什么吗?

编辑:

我想我将不得不从问题的根源开始。有一个私有地图数组,我试图从中获取名称列表。下面是 GetProgramList 的代码:

unsigned Effect::GetProgramList(vector<char*>& list) const
{
    for(map<string,Program*>::const_iterator it=m_programs.begin(); it!=m_programs.end(); ++it)
        list.push_back( (char*)it->first.c_str() );
}
4

3 回答 3

3

您可以char**像这样访问(但前提是您的编译器支持C++11):

    progList = list.data();
于 2013-01-04T21:18:12.400 回答
2

你为什么要投?

第一个char *元素的地址自动为 a char **,无需强制转换。如果这不起作用,请发布progList. 如果向量为空,这将导致未定义的行为并可能导致您的应用程序崩溃。确保list.size()大于 0(或!list.emty()- 更好)。

于 2013-01-04T21:12:55.147 回答
1

这:

 progList = &list[0];

应该可以完美运行。

但是因为:

std::vector<char*> list;

是函数的局部变量,它仅在函数处于活动状态时有效。一旦函数返回指针变得无效(因为向量不再存在)。

我提到这一点的原因是您似乎试图在progList这里用作输出参数:

int glfxGetProgramList(int effect, char** progList, int* count)


// Because you call like this:  
glfxGetProgramList(effect, list, &size );  // The value of list will not change
                                           // as you are passing by value.

fprintf(stderr, "Output: %s\n", list[0]);  // So here list has not changed.
                                           // But also note it would not have worked
                                           // as the object you were trying to make it 
                                           // point at would have gone out of scope.

不幸的是(或幸运的是)因为这些参数没有引用您在本地所做的任何更改都不会影响函数外部的原始值。

所以你需要修复几件事:

  • 使向量持续时间长于对函数的调用
  • 通过引用将列表传递给函数。

尝试:

int glfxGetProgramList(int effect, char**& progList, int* count)
                               //        ^  pass by reference
{
    static std::vector<char*> list; // Static makes the list last past the end of the function
    list.clear();                   // Now we have to clear it each time we call to make sure
                                    // that old results do not pollute the list.

    gEffects[effect]->GetProgramList(list);
    fprintf(stderr, "Lib Output: %s\n", list[0]);

    progList = &list[0];       // Value now passed correctly
                               // back to the calling function
                               // and list will still exist.

    int size = list.size();
    memcpy(count, &size, sizeof(int));  // This copies the first value out
}
于 2013-01-04T22:08:35.747 回答