gpt4 book ai didi

C++从二维动态数组中获取长度

转载 作者:行者123 更新时间:2023-11-30 01:52:31 25 4
gpt4 key购买 nike

我被 C++ 二维动态数组卡住了。我想获取数组长度。这是代码:

#include <iostream>
using namespace std;
int dosomestuff(char **dict);
int main(){
int x, y;
char **dict;
cin>>x>>y; // here to input the 'x'
dict = new char *[x];
for(i = 0; i < x; i++){
dict[i] = new char[y];
for(j = 0; j < y; j++){
cin>>dict[i][j];
}
}
dosomestuff(dict);
}
int dosomestuff(char **dict){
int x, y;
x = sizeof(*dict); //8 not equal to the 'x'
//run in mac_64 I think this is the pointer's length
y = strlen(dict[0]); //this equal to the 'y' in function main
cout<<x<<" "<<y<<endl;
return 0;
}

我想要的是在函数 dosomestuff 中使 x 等于函数 main 中的“x”。

我怎样才能得到它?谁能帮帮我~?非常感谢。

最佳答案

sizeof(*dict) 只给你 sizeof(char*),这不是你所希望的。

无法从 dosomestuff 中的 dict 获知 x 的值。如果你想为 dict 使用 char**,最好的选择是将 xy 传递给 dosomestuff.

int dosomestuff(char **dict, int x, int y);

由于您使用的是 C++,因此您可以使用:

std::vector<std::string> dict;

然后,如果您将 dict 传递给它,您将在 dosomestuff 中获得所需的所有信息。

关于C++从二维动态数组中获取长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24443312/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com