简体   繁体   English

如何返回一维尺寸未知的二维数组?

[英]How to return a 2d array where one dimension is of unknown size?

This is related to this question . 这与这个问题有关 I have a function void doConfig(mappings, int& numOfMappings) and I'm not sure how to declare mappings. 我有一个函数void doConfig(mappings, int& numOfMappings) ,我不确定如何声明映射。 It is a two dimensional array whose elements are chars. 它是一个二维数组,其元素为char。 The first dimension is determined at run time, and will be computed in the body of the function. 第一维在运行时确定,并将在函数主体中计算。 The second dimension is always going to be 2. What is the code for this? 第二维始终为2。此代码是什么? I'd imagine it to be char** mappings or something like that. 我想象它是char** mappings或类似的东西。 Also in C++ arrays are always passed by reference right? 同样在C ++中,数组总是通过引用传递吗? So I don't need to use & even though I intend to use the value when the function returns? 因此&即使我打算在函数返回时使用该值,也不需要使用&

EDIT: Basically I want to return this char (*mapping)[2] = new char[numOfMappings][2]; 编辑:基本上我想返回此 char (*mapping)[2] = new char[numOfMappings][2];

as per 2to1mux's suggestion I still cannot get it to work. 按照2to1mux的建议,我仍然无法正常工作。 The array appears to getting the right values but something is going wrong when the doConfig() function returns. 数组似乎获得了正确的值,但是当doConfig()函数返回时出现了问题。

int main()
{
    int numOfMappings = 0;
    char **mappings;
    doConfig(mappings, numOfMappings);
    cout << "This is mappings" << mappings << endl;//this address is different than the one given in doConfig(), is that wrong?
    cout << "this is numOfMappings: " << numOfMappings << endl;
    cout << mappings[0][0] << "->" << mappings[0][1] << endl;//program crashes here
    //code removed
    return EXIT_SUCCESS;
}

void doConfig(char **mappings, int& numOfMappings)
{
    //code removed, numOfMappings calculated
    for(int j = 0; j < numOfMappings; j++)
    {
        getline(settingsFile, setting);
        mappings[j] = new char[2];
        mappings[j][0] = setting.at(0);
        mappings[j][1] = setting.at(2);
    }
    for(int j = 0; j < numOfMappings; j++)
        cout << mappings[j][0] << "->" << mappings[j][1] << endl;//everything is as expected so array created ok
    cout << "This is mappings" << mappings << endl;//different address than the one give in main
}

OK I got it working now but mainly from haking around. 好吧,我现在可以正常工作了,但主要是因为闲逛。 Could people please explain there solutions as to how they known when to use * and & ? 人们能否在此解释有关如何知道何时使用*&解决方案?

Since you tagged you question C++, not C, I guess you might want a proper solution. 由于您标记的是C ++而不是C,所以我想您可能需要一个适当的解决方案。

template<typename T>
using vectorOf2D = std::vector<std::array<T, 2>>;

vectorOf2D<char> getMappings() {
    return /* whatever you do to fill those */;
    // (most probably) using NRVO to ellide the copy
}

And if you are afraid access might be complicated: 而且,如果您担心访问可能会很复杂:

auto mappings = getMappings();

functionTakingAMapping(mappings[i]);
char element = mappings[0][1];

(Following up on my answer to the linked question.) (紧随我对链接问题的回答。)

The direct (yet rather convoluted) syntax for this would be 直接的(至今相当复杂的)语法是

char (*create_mappings(size_t n))[2]
{
  // Allocate an char[n][2] array
  char (*mappings)[2] = new char[n][2];

  // Initailize `mappings[i][j]` in any way you want...

  return mappings;
}

But a better idea would be to make it more readable through typedef 但是更好的主意是通过typedef使其更具可读性

typedef char Char2[2];

Char2 *create_mappings(size_t n)
{
  // Allocate an char[n][2] array
  Char2 *mappings = new Char2[n];

  // Initailize `mappings[i][j]` in any way you want...

  return mappings;
}

I'll answer your questions last-in-first-out: 我会先后回答您的问题:

  1. Correct, you won't need to use & here. 正确,您无需在此处使用&

  2. The term by-reference technically doesn't apply to passing arrays, but the simple answer to your question is that you are never passing a copy of an array to a function. 从技术上讲,“按引用”一词不适用于传递数组,但是对您的问题的简单回答是,您永远不会将数组的副本传递给函数。 Any changes made to a parameter of type array will apply to the original array, not a copy. 对array类型的参数所做的任何更改都将应用于原始数组,而不是副本。

  3. I suggest passing a double-pointer: 我建议传递一个双指针:

     void doConfig(char **mappings, int& numOfMappings) 

    You will be able to access members of mappings exactly as you would a 2d array. 您将能够像访问二维数组一样完全访问映射成员。 Example: 例:

     mappings[2][3] = 'b'; 

EDIT: Here is new suggestion based on your clarification 编辑:这是根据您的澄清提出的新建议

void doConfig(char** mappings, int& numOfMappings){

    /*Compute numOfMappings -- 
      this integer is passed by-reference, so it can be used outside function
      to figure out the size allocated within the function*/

    mappings = new char*[numOfMappings];
    for(int i=0; i < numOfMappings; i++){
        mappings[i] = new char[2];
    }
    /*Do whatever you need to do with mappings*/

    /*Return nothing because function is void -- since mappings is passed as
      pointer, changes are maintained after function ends*/

}

You can return a pointer to the 2D array. 您可以返回一个指向2D数组的指针。

For example, 例如,

char **ptr;


return ptr;

While passing the address of arrays you don't have to use the & operator, if you want to pass the address of the starting location of the 2D array rather than the address of a particular element. 传递数组的地址时,如果要传递2D数组起始位置的地址而不是特定元素的地址,则不必使用&运算符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM