碰撞与2D C风格的数组 [英] Crash with 2D C-style arrays

查看:137
本文介绍了碰撞与2D C风格的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

与2D C风格的数组的一个常见问题。这个程序编译,但崩溃时打印()函数被调用:

A common problem with 2D C-style arrays. This program compiles, but crashes when the Print() function is called:

#include <iostream>
using namespace std;

static const int sx = 5, sy = 3;
static double M[sy][sx] = { { 0.0, 1.0, 2.0, 3.0, 4.0 },
                            { 0.1, 1.1, 2.1, 3.1, 4.1 },
                            { 0.2, 1.2, 2.2, 3.2, 4.2 } };

void Print(double **M, int j, int i)
{
    cerr << M[j][i] << endl;
}

int main()
{
    cerr << M[2][3] << endl;             // Prints 3.2
    Print((double**)&M[0][0], 2, 3);     // Crash
}

什么是错误的,我code?

What is wrong in my code?

是否有可能使其工作在不改变打印()的签名?

Is it possible to make it work without changing Print()'s signature?

该数组是不是动态的。

推荐答案

static double M[sy][sx] = { { 0.0, 1.0, 2.0, 3.0, 4.0 },
                            { 0.1, 1.1, 2.1, 3.1, 4.1 },
                            { 0.2, 1.2, 2.2, 3.2, 4.2 } };

什么是远程像双** ,而且它还是在其任何转换为​​这样的类型不正确。如果您在使用数组(称为一个二维数组,如果你想)的固定阵列,一个兼容的打印功能可以使用模板来制作的:

is nothing remotely like a double**, and casting it or anything within it to such a type is incorrect. If you're using a fixed arrays of arrays (call it a 2D array if you want), a compliant print function can be crafted using a template:

#include <iostream>
using namespace std;

static const int sx = 5, sy = 3;
static double M[sy][sx] = { { 0.0, 1.0, 2.0, 3.0, 4.0 },
                            { 0.1, 1.1, 2.1, 3.1, 4.1 },
                            { 0.2, 1.2, 2.2, 3.2, 4.2 } };


template<int M>
void Print( double(*ar)[M] , int j, int i )
{
    std::cout << ar[j][i] << '\n';
}

int main()
{
    Print(M, 2, 3);
    return 0;
}

这篇关于碰撞与2D C风格的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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