【发布时间】:2015-11-27 18:18:01
【问题描述】:
我需要使用一个大小未知的字符串数组。这里我有一个例子,看看是否一切正常。我需要知道 ClassC 中数组的大小,但不将该值作为参数传递。我已经看到了很多方法(这里和谷歌),但正如你现在所看到的,它们没有用。它们返回数组第一个位置的字符数。
void ClassB::SetValue()
{
std::string *str;
str = new std::string[2]; // I set 2 to do this example, lately it will be a value from another place
str[0] ="hello" ;
str[1] = "how are you";
var->setStr(str);
}
现在,如果我在 ClassC 中调试,strdesc[0] ="hello" and strdesc[1] = "how are you",所以我想 C 类正在获取信息 ok....
void classC::setStr(const std::string strdesc[])
{
int a = strdesc->size(); // Returns 5
int c = sizeof(strdesc)/sizeof(strdesc[0]); // Returns 1 because each sizeof returns 5
int b=strdesc[0].size(); // returns 5
std::wstring *descriptions = new std::wstring[?];
}
所以..在classC中,我怎么知道strdesc的数组大小,应该返回2??我也试过:
int i = 0;
while(!strdesc[i].empty()) ++i;
但在i=2 之后,程序因分段错误而崩溃。
谢谢,
使用可能的解决方案进行编辑:
结论:一旦我将数组的指针传递给另一个函数,就无法知道数组的大小
- 将大小传递给该函数...或...
- 使用带有 std::vector 类的向量。
【问题讨论】:
-
使用
std::vector<string>。 -
没有(标准)方法可以获取您的大小,只有一个指针,您需要自己跟踪它。在指针上执行
sizeof会得到指针的大小(通常在 32 位系统上为 4,在 64 位系统上为 8)。 -
除非您将其作为已知大小的类型(fx
std::vector<string>或const std::string strdesc[2])传递,否则您不能。 -
顺便说一句...“有很多方法可以做到(这里和谷歌),但你现在会看到”......我不知道,我也看不到任何会为代码中的字符串数组工作...只是在编写 c++ 时不要使用 c 样式数组
-
在不相关的注释上,
sizeof(strdesc[0])将不返回strdesc[0].size()。没有现实的编译器会让sizeof(std::string)等于 5。通常您有至少 8 个字节(指针大小的两倍,开始和结束或开始和长度)。
标签: c++ arrays string stdstring