【问题标题】:Passing a two-dimensional array to a struct (C++)将二维数组传递给结构(C++)
【发布时间】:2014-05-28 08:50:32
【问题描述】:

我遇到了一个包含指针和二维数组的问题。

我有一个结构,看起来像这样:

typedef struct {
    int row;
    int col;
    int **a;
} TEST;

现在我想将该类型的对象用于其他功能。但是我在将二维数组传递给该类型的对象时遇到问题。

例如我试过这个:

int main(int argc, char * argv[]){
    //Just to fill an array with some integers
    int rows = 3;
    int cols = 3;

    int a[rows][cols];

    srand(time(NULL));

    for (int x = 0; x < rows; x++){
        for (int y = 0; y < cols; y++){
            a[x][y] = rand() % 10 + 1;
        }
    }

    TEST * t = (TEST *) calloc(1,sizeof(TEST));
    t->row = rows;
    t->col = cols;
    t->a = a;

    return 0;
}

我怎样才能正确地做到这一点?

感谢您的帮助。

【问题讨论】:

  • 为什么是calloc?为什么是指针而不是std::vector
  • 您是否使用了错误的标签?你确定你想要 c++ 而不是 c?

标签: c++ arrays pointers multidimensional-array


【解决方案1】:

如果您需要动态分配 TEST 对象,则可以这样做:

int main(int argc, char * argv[])
{
    //Just to fill an array with some integers
    int rows = 3;
    int cols = 3;

    TEST* t = new TEST;
    t->row = rows;
    t->col = cols;
    t->a = new int*[rows];
    for(int i = 0; i < rows; i++)
       t->a[i] = new int[cols];    

    srand(time(NULL));

    for (int x = 0; x < rows; x++){
        for (int y = 0; y < cols; y++){
            t->a[x][y] = rand() % 10 + 1;
        }
    }

    return 0;
}

【讨论】:

  • 感谢您的快速答复!但是我在这里仍然有一个小问题:如果我尝试编译您的代码,我会收到一条错误消息,上面写着“cols cannot be used in a constant-expression”(我必须翻译它,因为我没有使用英文软件)为此行:t->a = new int[rows][cols];
  • 对不起,我在浏览器中写了,没有意识到它不是那样工作的。所以我更新了我的代码。确保正确释放动态分配的内存。
猜你喜欢
  • 2014-03-15
  • 1970-01-01
  • 1970-01-01
  • 2021-05-10
  • 1970-01-01
相关资源
最近更新 更多