Treesrule14 Treesrule14 - 2 months ago 10
C Question

Illegal instruction upon operating on an array

Okay so I am trying to make a histogram from a three dimensional array of int in c.
Here is the line where I edit the array;

buckets[(int)floor(x/splits)][(int)floor(y/splits)][(int)floor(z/splits)]++;


x, y, z were generated earlier in the program (this is in a loop) splits was asked as input from the user. Then I try to put this data into a histogram and the compiler is giving me an illegal instruction.

histogram[(int)buckets[i][j][k]]++;


I am pretty sure it is here because I put print statements in the program which worked until this point but not afterwords. Here is all of the relavent code.

ff=fopen(fname,"r");
int buckets[split][split][split];
splits = (double) 1/split;
for(i=0; i<split; i++){
fscanf(ff,"%lf",&x);
fscanf(ff,"%lf",&y);
fscanf(ff,"%lf",&z);
buckets[(int)floor(x/splits)][(int)floor(y/splits)][(int)floor(z/splits)]++;
fclose(ff);
}
int histogram[10];
for (i=0; i<split; i++) {
for (j=0; j<split; j++){
for(k=0;k<split;k++){
histogram[(int)buckets[i][j][k]]++;
}
}
}

Answer

When you define your array:

int buckets[split][split][split];

You do not initialize it with something like:

memset(buckets, 0x00, sizeof(int) * split * split * split);

So buckets has unknown values in it. You then increment these numbers, but when you do:

histogram[(int)buckets[i][j][k]]++;

buckets[i][j][k] could be equal to anything. Solution is to add the memset() after the array declaration.

Comments