The problem is the value
m
exceeds the limit of an integer so
i
will never reach it. Below shows how it can be fixed. I also have some suggestions.
1. As the first statement in your while loop, add this :
int nextN = n[next];
and then use
nextN
everywhere else that
n[next]
appears. That will make it easier when you are viewing variables while debugging.
2. Release all the memory you are allocating as soon as you are finished with it. If I were you, I would make a function to allocate two dimensional arrays of memory and another one to release them. Since this is c++, normally I would use a vector of vectors or a template function with arrays but neither are likely to be appropriate here. Therefore, I would settle for a pair of functions that could do this. Here are examples:
typedef int * pint;
typedef pint * ppint;
ppint Allocate2Darray( int dim1, int dim2 )
{
ppint ptrs = new pint[ dim1 ];
for( int n = 0; n < dim1; ++n )
ptrs[ n ] = new int[ dim2 ];
return ptrs;
}
void Release2Darray( ppint & ptrs, int dim1 )
{
for( int n = 0; n < dim1; ++n )
delete [] ptrs[ n ];
delete [] ptrs;
ptrs = nullptr;
}
3. Use constant values instead of literal values. To be specific :
const int ValueCount = 6;
Combining all of these, your code could be :
const int ValueCount = 6;
int main()
{
const int n[ValueCount] = {16, 64, 256, 1024, 4096, 16384};
int a, b, x;
int next = 0;
while (next < ValueCount)
{
int nextN = n[ next ];
ppint M = Allocate2Darray( nextN, nextN );
for (int i = 0; i < nextN; i++) {
for (int j = 0; j < nextN; j++) {
M[i][j] = 0;
}
}
time_t timer;
timer = clock();
const size_t count = 13421772800;
for (size_t i = 0; i < count; i++) {
x = rand() % 100 + 1;
b = rand() % nextN;
a = rand() % nextN;
M[a][b] += x;
}
timer = clock() - timer;
printf("Clock time for n size %d: %.3f seconds\n", n[next], (float)timer / CLOCKS_PER_SEC);
Release2Darray( M, next );
next++;
}
return 0;
}
Note that I added a few
const
statements where appropriate.