如何解决如何在多维数组中创建和存储字符串数据?
如何使用指针在多维数组中创建和存储字符串数据?我的尝试是:
cofig/initializers/activereport_sqlserver_adapter.rb
解决方法
初始化的第一行有错误。 如果要避免任何错误,请像这样初始化它。
string** arr = new string*[3];
/* It will have count of rows of string you will have like in this statement 3 rows of string. */
// Now you will have to tell about columns for each row separately.
for(int i = 0; i < 3; i++) {
arr[i] = new string[2]; // Here you are initializing each row has 2 columns
}
// Now write your code below...
,
您可以按以下方式重写您的代码:
string **arr = new string*[3]; // row 3
for(unsigned i = 0; i < 3; i++)
arr[i] = new string[2](); // column 2
arr[0][0] = "first"; arr[0][1] = "second";
for(unsigned i = 0; i < 3; i++){. // yours ans
for(unsigned j = 0; j < 2; j++)
cout << arr[i][j] << " ";
cout << '\n';
}
,
如果您希望能够使用{"first","second"}
初始化整个子数组,则很可能需要使用std::vector
或std::array
而不是手动分配内存用于数组。除非您有使用指针的特殊原因,否则使用向量的外观如下:
using str_vec = std::vector<std::string>;
std::vector<str_vec> v(3,str_vec(2,""));
v[0] = {"first","second"};
但是,如果您确实需要指针,则必须先为“行”分配内存,然后为每个“列”分别分配内存:
std::string** a = new std::string*[3];
for(int i = 0; i < 3; ++i) {
a[i] = new std::string[2];
}
之后,您可以一个一个地填充值:
a[0][0] = "first";
a[0][1] = "second";
完成操作后,不要忘记删除所有这些数组。以相反的顺序,您首先需要删除所有列,然后删除“行”:
for(int i = 0; i < 3; ++i) {
delete[] a[i];
}
delete[] a;
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。