C获取字符串数组的大小

我需要使用大小未知的字符串数组.在这里,我有一个例子,看看是否一切正常.我需要在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] =“你好”和strdesc [1] =“你好吗”,所以我认为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[?];
}

那么..在classC中,我怎么知道strdesc的数组大小,应该返回2?我也尝试过:

int i = 0;
while(!strdesc[i].empty()) ++i;

但是在i = 2之后,程序崩溃并出现分段错误.

谢谢,

使用可能的解决方案进行编辑:

结论:一旦我将指针传递给另一个函数,就无法知道数组的大小

>将大小传递给该函数……或者……
>使用带有std :: vector类的向量.

最佳答案

how can I know strdesc’s array size

您无法从指向该数组的指针知道数组的大小.

你可以做的是将大小作为另一个参数传递.或者甚至更好,使用矢量代替.

but after i=2 the program crashes with a segmentation fault.

访问数组边界之外的行为是未定义的.

点赞