C ++获取字符串数组的大小

时间:2015-09-02 09:42:52

标签: c++ arrays string stdstring

我需要使用大小未知的字符串数组。在这里,我有一个例子,看看是否一切正常。我需要在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类正在获取信息确定....

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之后程序崩溃并出现分段错误。

谢谢,

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

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

  1. 将尺寸传递给该功能......或......
  2. 使用带有std :: vector class的向量。

2 个答案:

答案 0 :(得分:1)

使用这种代码会导致内存泄漏和其他类型的C风格问​​题。

使用vector:

    #include <vector>
    #include <string>
    #include <iostream>
    ...
    std::vector<std::string> my_strings;
    my_strings.push_back("Hello");
    my_strings.push_back("World");

    std::cout << "I got "<< my_strings.size() << " strings." << std::endl;

    for (auto& c : my_strings)
            std::cout << c << std::endl;

答案 1 :(得分:1)

  

我怎么知道strdesc的数组大小

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

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

  

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

超出数组边界的访问具有未定义的行为。

相关问题