I want to create a N*N array with default value -1 in cpp, I tried many ways like memset, fill, fill_n but non of them worked...
here's my code:
N = 10;
int **m = new int*[N];
for(int i = 0; i < N; ++i) {
int a[N];
fill_n(a, N, -1);
for(int j = 0; j < N; j++)
cout << a[j] << endl; // values here are all -1
m[i] = a;
// m[i] = new int[N];
}
// memset(m, -1, sizeof(m));
for(int i=0; i < N; i++) {
for(int j = 0; j < N; j++) {
// value output here are wrong, looks like random numbers
cout << "[" << i << "][" << j << "]" << m[i][j] << endl;
}
}
output value are
[0][0]7
[0][1]32625
[0][2]2045453384
[0][3]21958
[0][4]-279530816
[0][5]32767
[0][6]-1010169277
[0][7]32625
[0][8]-279532512
[0][9]32767
[0][10]2036459499
[0][11]21958
[1][0]-1009461504
[1][1]32625
[1][2]2045453384
[1][3]21958
[1][4]-279530816
[1][5]32767
[1][6]-1010169277
[1][7]32625
...
In contrast, when I assign with two for loops, it can work correctly...
for(int i = 0; i < N; i ++)
for(int j = 0; j < N; j++)
m[i][j] = -1;
for(int i=0; i < N; i++) {
int *p = m[i];
for(int j = 0; j < N; j++) {
int a = p[j];
cout << "[" << i << "][" << j << "]" << a << endl;
}
}
However, N ranges from 10 to 100,000, so I can't use forloop to construct such huge array...
what did I do wrong?
int a[N];is not legal C++ code to begin with. Then you dom[i] = a;right beforeagoes out of scope, leavingm[i]dangling.