Hi.
I have written a program to build an array and move values around until a point of "equilibrium" is reached. It then records how many of each number there are and outputs them to a file. My program works in part, but sometimes encounters a seg fault (I think I'm over running an array but can't see where).
I would appreciate if someone could find the source of this and any other problems with my program (anything at all!)
Here's my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
int main ( void )
{
int i, j, k, **lattice = 0, row, col, sum = 0;
int average, check, pcntlatt, table[15][2], startlim;
FILE *output;
const char out_fn[]="0604632_proj2.out";
row = 5;
col = 5;
startlim = 5;
lattice = malloc (row * sizeof(int *));
srand ( (unsigned)time ( NULL ) );
for(i = 0; i < row; i++)
{
lattice[i] = malloc(col * sizeof(int));
}
for(k = 0; k < (11); k++)
{
table[k][0] = k;
}
for(i = 0; i < row; i++)
{
for (j = 0; j < col; j++)
{
lattice[i][j] = rand() / ( RAND_MAX / startlim + 1 );
}
}
pcntlatt = (3*row*col)/5;
table[0][1] = 0;
while (table[0][1] < pcntlatt)
{
table[0][1] = 0;
table[1][1] = 0;
table[2][1] = 0;
table[3][1] = 0;
table[4][1] = 0;
table[5][1] = 0;
table[6][1] = 0;
table[7][1] = 0;
table[8][1] = 0;
table[9][1] = 0;
table[10][1] = 0;
table[11][1] = 0;
table[12][1] = 0;
table[13][1] = 0;
table[14][1] = 0;
table[15][1] = 0;
i = rand() / (RAND_MAX / row);
j = rand() / (RAND_MAX / col);
if (lattice [i][j] != 0)
{
lattice[i][j] = (lattice [i][j])--;
i = rand() / (RAND_MAX / row);
j = rand() / (RAND_MAX / col);
lattice[i][j] = (lattice [i][j])++;
}
for (i = 0; i < row; i++)
{
for (j = 0; j < col; j++)
{
switch (lattice[i][j])
{
case 0:
table[0][1] = table[0][1]++;
break;
case 1:
table[1][1] = table[1][1]++;
break;
case 2:
table[2][1] = table[2][1]++;
break;
case 3:
table[3][1] = table[3][1]++;
break;
case 4:
table[4][1] = table[4][1]++;
break;
case 5:
table[5][1] = table[5][1]++;
break;
case 6:
table[6][1] = table[6][1]++;
break;
case 7:
table[7][1] = table[7][1]++;
break;
case 8:
table[8][1] = table[8][1]++;
break;
case 9:
table[9][1] = table[9][1]++;
break;
case 10:
table[10][1] = table[10][1]++;
break;
case 11:
table[11][1] = table[11][1]++;
break;
case 12:
table[12][1] = table[12][1]++;
break;
case 13:
table[13][1] = table[13][1]++;
break;
case 14:
table[14][1] = table[14][1]++;
break;
case 15:
table[15][1] = table[15][1]++;
break;
default:
break;
}
}
}
}
output = fopen ("0604632_proj2.out", "w");
for (k = 0; k < (11); k++)
{
printf("%d %d\n", table[k][0], table[k][1]);
fprintf(output, "%d %d\n", table[k][0], table[k][1]);
}
fclose(output);
return (0);
}