新的多维数组分配 [英] Multidimentional Array allocation with new

查看:67
本文介绍了新的多维数组分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,

我对新的和多维分配有一个小问题:

我的代码如下:

Hello,

I have a little issue with new and multidimentional allocation :

my code is as below :

void reset_board(int **a,int num_row)
{

	a = new int*[num_row];
	for(int i = 0; i < num_row; i++)
		a[i] = new int[num_row];

	for (int i=0; i< num_row ; i++)
		for (int j=0; j< num_row ; j++)
			a[i][j] = i+j;
}

int main()
{
	int **a = new int *[];
	
	reset_board(a,4);

	for (int i=0; i< 4 ; i++)
		for (int j=0; j< 4 ; j++)
			cout << a[i][j]<< endl ;
	return 0;
}



问题是:在功能上矩阵已经很满了,我可以在屏幕上写它的内容,但是当我尝试显示它崩溃的内容时,主要是临时var没有隐式分配给矩阵.


我该如何解决?谢谢



the prob is : in the fucntion the matrix is well full and i could write its content on the screen but in the main when i try to show the content it s crashes, it''s like the temporary var is not implicitly allocated to the matrix.


How could i resolve that ? Thank you

推荐答案

将reset_board的签名更改为
Change the signature of reset_board to
void reset_board(int **&a,int num_row)



如果要更改"a"本身,则需要引用或指针指向"a",否则reset_board中的局部变量"a"将获得新值,而"a"



You want a reference or pointer to ''a'' if you''re going to change ''a'' itself, otherwise the local variable ''a'' in reset_board is getting a new value, and the ''a'' from main is not.


由于您使用C ++进行编程,因此不能简单地使用向量吗?

更安全,更清洁,更现代.

像这样的东西:
Since you are programming in C++, couldn''t you simply use vectors ?

It''s safer, cleaner, and more modern.

something like that:
void reset_board(std::vector < std::vector <int> >& a,int num_row)
{
    a.resize(num_row);
    for(int i = 0; i < num_row; i++)
    {
        a[i].resize(num_row);
    }

    for (int i=0; i< num_row ; i++)
    {
        for (int j=0; j< num_row ; j++)
        {
            a[i][j] = i+j;
        }
    }
}

int _tmain(int argc, _TCHAR* argv[])
{
    std::vector < std::vector <int> > a;

    reset_board(a,4);

    for (int i=0; i< 4 ; i++)
    {
        for (int j=0; j< 4 ; j++)
        {
            std::cout << a[i][j]<< " ";
        }

        std::cout << std::endl;
    }

}


这篇关于新的多维数组分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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