dynamic multidimensional array c++ Probleme

Hello everyone

first thing is first here is the code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <stdlib.h>
using namespace std;

int main(int argc, char *argv[]){
    int i,j,row,col;
    row = atoi(argv[1]);
    col = atoi(argv[2]);
    double **I = new double*[row];
    for(i=0;i<col;i++){
        I[i] = new double[col];
    }

    for(i=0;i<row;i++){
        for(j=0;j<col;j++){
            I[i][j]=0;
        }
    }
}


now let's talk so i was trying to make a dynamic multidimensional array in c++ so i did some research and i came up with code above which actually work pretty fine but not that fine in fact if i try this
1
2
3
4
5
~$ g++ main.cpp -o testmain
~$ ./testmain 10 10
~$ ./testmain 12 10
Segmentation fault (core dumped)
~$ ./testmain 10 12


i tryed this both on windows and linux and they both do the same thing in fact if i try to make an array with rows=colons it wotk it even work if rows<colons but it dosn't work if rows >colons and sometimes even rows<colons dosn't work

Any Ideas

Thanks
Last edited on
line 10 and 20: col needs to be row
line 10 is a mistake:

for(i=0;i<col/* <- should be row*/; i++){


EDIT:

And of course... if you're dynamically allocating, you must remember to delete the memory when you're done:

1
2
3
    for(i=0;i<row;i++)
        delete[] I[i];
    delete[] I;
Last edited on
The reason it doesn't work when row < colons is because of the condition on lines 10 and 20.

double **I = new double*[row]; creates an array of pointers of length row.

On lines 10 and 20, you are iterating over the array of pointers, col times! So when col <= row, this code seems to work but when col > row, then sht hits the fan and you get that ugly mess.
Thank You sooooooooo much (all of you) i didn't even notice that
Topic archived. No new replies allowed.