获取字符串数组的大小

C++ getting the size of an array of strings

本文关键字:数组 字符串 获取      更新时间:2023-10-16

我需要使用一个未知大小的字符串数组。这里我有一个例子,看看是否所有工作正常。我需要知道数组的大小在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[?];
}

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

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

但是在i=2之后,程序由于分割错误而崩溃。

谢谢,

Edit with the possible SOLUTIONS:

结论:一旦将数组的指针传递给另一个函数 ,就无法知道数组的大小。
  1. 将大小传递给该函数…还是…
  2. 在std::vector类中使用vector

如何知道strdesc的数组大小

不能通过指向数组的指针知道数组的大小。

你能做的是传递大小作为另一个参数。或者更好的是,使用vector。

,但当i=2后,程序因分段错误而崩溃。

在数组边界之外访问有未定义的行为

使用这种代码,您将获得内存泄漏和其他类型的c风格问题。

使用向量:

    #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;