How to deallocate a matrix

W

Wei-Chao Hsu

The program always crashs where the memory is deallocated. Any one could
help me? Thanks!

#include <iostream>

void main()
{
//Allocate
int **a=new int* [4];
for(int i=0;i<10;++i)
a=new int [10];


for(int i=0;i<4;++i)
for(int j=0;j<10;++j)
a[j]=100*i+j;

for(int i=0;i<4;++i)
for(int j=0;j<10;++j)
std::cout<<a[j]<<std::endl;

//Deallocate
for(int i=0;i<4;++i)
delete [] a;
delete [] a; //crash at here!

}
 
R

Robert Bauck Hamar

The program always crashs where the memory is deallocated. Any one could
help me? Thanks!

#include <iostream>

void main()

Should be int main()
{
//Allocate
int **a=new int* [4];
for(int i=0;i<10;++i)

Is 10 the correct number here?
a=new int [10];


for(int i=0;i<4;++i)
for(int j=0;j<10;++j)
a[j]=100*i+j;

for(int i=0;i<4;++i)
for(int j=0;j<10;++j)
std::cout<<a[j]<<std::endl;

//Deallocate
for(int i=0;i<4;++i)
delete [] a;
delete [] a; //crash at here!


It probably has something to do with the first for loop writing to
memory it doesn't own.

A tip:
#include <vector>
#include <iostream>

int main()
{
//allocate
std::vector<std::vector<int> > a(4, std::vector<int>(10));
for (int i=0; i < a.size(); ++i)
for (int j=0; j < a.size(); ++j)
a[j] = 100*i+j;


for(int i=0;i<4;++i)
for(int j=0;j<10;++j)
std::cout<<a[j]<<std::endl;

//deallocation: automatic
}
 
I

Ian

Wei-Chao Hsu said:
The program always crashs where the memory is deallocated. Any one could
help me? Thanks!

#include <iostream>

void main()
{
//Allocate
int **a=new int* [4];
for(int i=0;i<10;++i)
a=new int [10];

Should that be for(int i=0;i<4;++i) ?

Ian
for(int i=0;i<4;++i)
for(int j=0;j<10;++j)
a[j]=100*i+j;

for(int i=0;i<4;++i)
for(int j=0;j<10;++j)
std::cout<<a[j]<<std::endl;

//Deallocate
for(int i=0;i<4;++i)
delete [] a;
delete [] a; //crash at here!

}
 
W

William Xuuu

Robert Bauck Hamar said:
A tip:
#include <vector>
#include <iostream>

int main()
{
//allocate
std::vector<std::vector<int> > a(4, std::vector<int>(10));
for (int i=0; i < a.size(); ++i)
for (int j=0; j < a.size(); ++j)
a[j] = 100*i+j;


for(int i=0;i<4;++i)
for(int j=0;j<10;++j)
std::cout<<a[j]<<std::endl;

//deallocation: automatic
}


Hmmh, your tip seems good when dealing with two dimension arrays. I'm wondering
whether there're some similar methods dealing with three, four, five,
.... dimension arrays. Huh?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top