Keith Thompson skrev:
"Sheldon" <sh******@gmail.comwrites:
I have a problem that and the answer eludes me:
I am converting a 2D array to a 1D array within a for loop that looks
something like this:
ii=0;
for (i = 0; i < 300; i++) {
for (j = 0; j < 250; j++) {
oneD1[ii] = TwoD1[i][j];
oneD2[ii] = TwoD2[i][j];
oneD3[ii] = TwoD3[i][j];
ii++;
}
}
I get a segmentation fault and when I print out ii, the values exceeds
the product of 300*250.
Why does this happen when ii starts at zero and increments with 1 after
use? Even if I change ii++ to ii += 1, the same thing happens.
Your actual code "looks something like this"? Obviously it doesn't
look exactly like what you posted, and the source of your problem is
probably one of the differences between your actual code and the loose
approximation you posted.
(It's obvious that changing ii++ to ii += 1 won't make any difference;
they do exactly the same thing.)
Don't make us guess. Show us real code that exhibits the problem.
--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
The code is over 1800 lines long and I didn't think it was appropriate
to post it all. The function IS this:
static int TwoDToOneD(void) {
int i,j, ii;
MALLOC(ret.lightcon, sizeof(float*)*AreaRow/res*AreaCol/res);
MALLOC(ret.valconcen, sizeof(int*)*AreaRow/res*AreaCol/res);
MALLOC(ret.bias100, sizeof(float*)*AreaRow/res*AreaCol/res);
MALLOC(ret.bias75, sizeof(float*)*AreaRow/res*AreaCol/res);
MALLOC(ret.bias50, sizeof(float*)*AreaRow/res*AreaCol/res);
MALLOC(ret.bias25, sizeof(float*)*AreaRow/res*AreaCol/res);
MALLOC(ret.latitude, sizeof(float*)*AreaRow/res*AreaCol/res);
MALLOC(ret.longitude, sizeof(float*)*AreaRow/res*AreaCol/res);
ii = 0;
printf("Row: %d\tCol: %d\n", AreaRow/res, AreaCol/res);
for (i = 0; i < AreaRow/res; i++) {
for (j = 0; j < AreaCol/res; j++) {
printf("ii: %d\ti: %d\tj: %d\n", ii, i, j);
ret.lightcon[ii] = work.lightcon2D[i][j];
ret.bias100[ii] = work.bias1002D[i][j];
ret.bias75[ii] = work.bias752D[i][j];
ret.bias50[ii] = work.bias502D[i][j];
ret.bias25[ii] = work.bias252D[i][j];
ret.latitude[ii] = work.latitude2D[i][j];
ret.longitude[ii] = work.longitude2D[i][j];
ret.valconcen[ii] = work.valconcen2D[i][j];
ii++;
}
}
for (i = 0; i < AreaCol; i++) {
free(work.lightcon2D[i]);
free(work.bias1002D[i]);
free(work.bias752D[i]);
free(work.bias502D[i]);
free(work.bias252D[i]);
free(work.latitude2D[i]);
free(work.longitude2D[i]);
free(work.valconcen2D[i]);
}
free(work.lightcon2D);
free(work.bias1002D);
free(work.bias752D);
free(work.bias502D);
free(work.bias252D);
free(work.latitude2D);
free(work.longitude2D);
free(work.valconcen2D);
return 1;
}