获取字符串数组的大小
C++ getting the size of an array of strings
我需要使用一个未知大小的字符串数组。这里我有一个例子,看看是否所有工作正常。我需要知道数组的大小在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:
结论:一旦将数组的指针传递给另一个函数 ,就无法知道数组的大小。- 将大小传递给该函数…还是…
- 在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;
相关文章:
- 使用 jsoncpp 解析 json 数组字符串
- C++ 对象数组字符串输入在控制台上不起作用
- 插入了 C++ 数组字符串数据,但在显示输出时不显示
- 无法区分 JSON 对象/数组/字符串
- 为什么数组(字符串类型)的大小是 24 字节,带有单个空格元素
- 如何使用数组字符串进行输入验证
- (C++) 打印字符数组字符串的单词时出现问题
- 使用Back_inserter从任何位置的输入字符中使用Back_inserter进行过滤数组字符串
- C 函数反转字符数组字符串
- 如何在 c++ 中创建数组(字符串 [] )的向量
- 如何返回数组字符串的指针
- char数组字符串混淆
- 如何从字符数组字符串中提取空格
- 是否可以将 Bitset<8> 的值复制到数组字符串而不转换它们?
- C++数组字符串函数
- 如何在函数中操作字符数组(字符串)的指针,该指针在C / C ++中作为参数传递
- visual将音频文件存储到数组/字符串流C++中
- c++在char数组(字符串)上将what替换为
- 将数组字符串转换为intger c++(初学者)
- 需要设置数组字符串长度,使其恰好为13