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

C++ get length from two dimensional dynamic array

本文关键字:数组 获取 动态 二维      更新时间:2023-10-16

我被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中所需的所有信息。