如何将静态2D数组的指针传递给结构/类? [英] How can I pass the pointer of a static 2D array to a structure/class?

查看:157
本文介绍了如何将静态2D数组的指针传递给结构/类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题,当我尝试传递数组(其中包含我的程序中的一些函数需要的参数)的指针到一个结构,然后应该传递给那些函数。 GSL例如要我以这种方式传递参数。

I have a problem when I try to pass the pointer of an array (which contains parameters needed by some functions in my program) to a structure, which then should be passed to those functions. GSL for example wants me to pass parameters in this way.

一个小示例程序看起来像这样:

A little example program looks like this:

#include <iostream>

using namespace std;

struct myparams
{
    double  * a;
    double ** b;
};

int main()
{
    double c[10]   = {0,1,2,3,4,5,6,7,8,9};
    double d[4][3] = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}};

    double** e = new double*[4];
    for (int i = 0; i < 4; i++) {
       e[i] = new double[3];
    }

    myparams params;

    // THIS WORKS:
    params.a = c;
    for (int i = 0; i < 10; i++) {
        cout << params.a[i] << endl;
    }

    // THIS DOESN'T WORK
    params.b = d;

    // THIS WORKS:
    params.b = e;

    delete[] e;
}

 params.b = d

不能将赋值或类似内容(从德语翻译)中的'double [4] [3]'转换为'double **'。

The Compiler complains with "cannot convert 'double[4][3]' to 'double**' in assignment" or something like that (translated from german).

推荐答案

double d [4] [3]; double b **; 是指向指针的指针。这些类型是不一样的(常见的数组只是指针,您可能已经在互联网上阅读错误)。

double d[4][3]; is an array of arrays. double b**; is a pointer to pointer. These types are not the same (the common "arrays are just pointers" you might have read on the internet is wrong).

元素 d 的类型为 double [3] 。数组在传递时衰减为指向其第一个元素的指针(参见C ++标准的第4.2节)。 d 将衰减到 double(*)[3] (指向3个双精度数组的指针)

Elements of d are of type double[3]. Arrays, when passed around, decay to pointers to their first element (see section 4.2. of C++ standard). d will decay to double(*)[3] (a pointer to array of 3 doubles).

长时间短, double(*)[3] 不能转换为 double ** 这是编译器告诉你的。

Long story short, double(*)[3] is not convertible to double** and this is what compiler is telling you.

如果你需要保留 d 它需要声明b为 double(* b)[3] ;

If you need to keep d as it is, you need to declare b as double (*b)[3];

深入解释,请参阅此SO问题

这篇关于如何将静态2D数组的指针传递给结构/类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆