Click here to Skip to main content
15,887,175 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello,

I have a little issue with new and multidimentional allocation :

my code is as below :

C++
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;
}


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
Posted

Change the signature of reset_board to
C++
void reset_board(int **&a,int num_row)


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.
 
Share this answer
 
v3
Comments
Schehaider_Aymen 6-Mar-12 14:47pm    
Yup, that was the trick ^^.
Thank You Lewax00
Since you are programming in C++, couldn't you simply use vectors ?

It's safer, cleaner, and more modern.

something like that:
C++
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;
    }

}
 
Share this answer
 
Comments
Schehaider_Aymen 6-Mar-12 14:41pm    
I know Maximilien, but i wanted to keep up my brain with pointers (i have almost 4 years that i did not usem them) Thanks indeed.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900