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

时间:2014-06-27 03:06:25

标签: c++ pointers dynamic-arrays

我被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等于&#39; x&#39;在功能主要。

我怎样才能得到它?任何人都可以帮帮我〜?很多。

1 个答案:

答案 0 :(得分:4)

sizeof(*dict)只会为您提供sizeof(char*),这不是您所希望的。

无法在x中了解dictdosomestuff的价值。如果您想char**使用dict,则最好选择将xy传递给dosomestuff

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

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

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

如果您将dosomestuff传递给dict,那么您将获得{{1}}所需的所有信息。

相关问题