在c ++中使用动态多维数组 [英] Using dynamic multi-dimensional arrays in c++

查看:122
本文介绍了在c ++中使用动态多维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个C ++程序,检查是否是一个拉丁广场。我需要使用存储给定的拉丁方形的动态多维数组。但我不能传递数组到一个函数,检查...

I am making a C++ program that checks if given aray is a latin square. I need to use a dynamic multi-dimensional array that stores given latin square. But I cant pass the array to a function that does the checking...

目前我有这样的代码调用函数:

Currently I have such code for calling the function:

int squaretest(int **p, int n, int sum) {

    //some code
};

此代码用于创建数组:

int main() { 

    //some code. n - length of one row, sum - sum of elements in one row.
    int a;	
    int **lsquare;
    lsquare = new int*[n];
    for (int i=0;i<=n-1;i++) for (int j=0;j<=n-1;j++) {
    	cin >>a;
    	lsquare[i][j] = a;
    }
    blocktest(lsquare,n,sum);
    //some code
};

代码编译(我使用Geany IDE和G ++编译器),但是当我在终端运行它时,在第一个输入之后,必须存储在块[0] [0]中,我得到分段故障错误。我的代码有什么问题,什么是正确的解决方案?

The code compiles (i am using Geany IDE and G++ compiler) but when I run it in terminal, after the first imput, that has to be stored in block[0][0] I get Segmentation fault error. What's wrong with my code and what is the correct sollution?

推荐答案

this:

int **lsquare = new int*[n];

for (int i=0; i<n; ++i)
    lquare[i] = new int[n];

for (int i=0; i<n; i++)
    for (int j=0; j<n; j++)
        cin >> lsquare[i][j];

blocktest(lsquare,n,sum);

更好的系统是:

int *lsquare = new int[n*n];

for (int i=0; i<n; ++i)
    for (int j=0; j<n; ++j)
        cin >> lsquare[i + j*n];

blocktest(lsquare, n, sum);

这篇关于在c ++中使用动态多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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