我需要使用一个字符串数组,但它的大小未知。这里有一个示例代码,以确保一切正常。但是,我需要在ClassC中获得该数组的大小,而无需将该值作为参数传递。我已经尝试过许多方法(包括在Google上搜索),但是如您现在所看到的,它们都不起作用。它们只返回数组第一个位置中字符的数量。
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"
和strdesc [1] = "how are you"
,我认为Class C已经正确获取了信息...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[?];
}
那么,在C类中,我应该如何知道strdesc的数组大小,应该返回2? 我也尝试过:
int i = 0;
while(!strdesc[i].empty()) ++i;
但是,在i=2
之后,程序崩溃并出现分段错误。
谢谢,
可能的解决方案:
结论:一旦将数组指针传递给另一个函数,就无法知道数组的大小。
- 将大小传递给该函数... 或者...
- 使用std::vector类的向量。
std::vector<string>
。 - 463035818_is_not_a_numbersizeof
将给出指针的大小(通常情况下,在 32 位系统上为 4,在 64 位系统上为 8)。 - Some programmer dudestd::vector<string>
或const std::string strdesc [2]
),否则您无法这样做。 - skykingsizeof(strdesc[0])
不会 返回strdesc[0].size()
。现实的编译器也不会使sizeof(std::string)
等于 5。通常你至少有 8 个字节(指针的两倍大小,开始和结束或开始和长度)。 - MSalters