我是C ++的新手,并且正在努力使以下代码工作:
struct Keywords
{
const char* const* keys;
int count;
}
Keywords GetKeywords()
{
Keywords keywords;
keywords.count = 10;
string keys = "a b c d e";
keywords.keys = keys???;
return keywords;
}
int main(int argc, char *argv[])
{
Keywords keywords = GetKeywords();
cout<<keywords.count<<endl; //prints 10
cout<<keywords.keys<<endl; //prints a memory address like 0030F838
}
如何让keys
指向a b c d e
?
到目前为止,我已经尝试了这个
char * writable = new char[keys.size() + 1];
strcpy(writable, keys.c_str());
writable[keys.size()] = '\0';
const char* a = writable;
const char** ptr = &a;
results.keys = ptr;
调试时我可以看到results.keys
显示a b c d e
,但只要GetKeywords()
返回,results.keys
就会指向不可读的内存位置。
我无法对struct Keywords
和GetKeywords()
方法签名进行任何更改。
答案 0 :(得分:0)
考虑到Some programmer dude,Miles Budnek和其他人提供的提示,我能够解决问题,如下所述:
在我原来的问题中,密钥由string keys = "a b c d e";
表示。
但是,我在a b c d e
上工作的作业是通过迭代set<string>
项来构建的。所以这是如何完成的:
struct Keywords
{
const char* const* keys;
int count;
}
Keywords GetKeywords()
{
Keywords keywords;
keywords.count = 5;
set<string> keys;
GetKeys(keys);//returns keys = {"a", "b", "c", "d", "e"}
char** charKeysPtr = new char *[keys.size() + 1];
set<string>::iterator it;
int index = 0;
//Iterate the set and copy each key
for (it = keys.begin(); it != keys.end(); it++)
{
charKeysPtr[index] = new char[it->size() + 1];
strcpy(charKeysPtr[index], it->c_str());
charKeysPtr[index][it->size()] = '\0';
index++;
}
keywords.Keys = charKeysPtr;
return keywords;
}
int main(int argc, char *argv[])
{
Keywords keywords = GetKeywords();
//Print keys
for (int i = 0; i < keywords.count; ++i)
cout << keywords.keys[i] << " ";
//Output is "a b c d e"
//Memory cleanup and etc.
}
谢谢你们!