Search code examples
c++pointersdynamic-arrays

C++ get length from two dimensional dynamic array


I have got stuck by the C++ two dimensional dynamic array. I want to get the array length. Here is the code:

#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;
}

What I want is in function dosomestuff to get the x equal the 'x' in function main.

How can I to get it? Can anybody help me ~? Thx a lot.


Solution

  • sizeof(*dict) only gives you the sizeof(char*), which is not what you are hoping for.

    There is no way of knowing the value of x from dict in dosomestuff. If you want to use char** for dict, your best option is to pass x and y to dosomestuff.

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

    Since you are using C++, you can use:

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

    Then you would have all the information you need in dosomestuff if you pass that dict to it.