Pointer to a 2 dimensional array?

B

Ben Bacarisse

Louise Hoffman said:
Okay, found at least one bug in fit_data.c

p[ybin*(X_BINS-1) + xbin] = '*';

should have been:

p[ybin*(X_BINS) + xbin] = '*';

But now I get segmentation fault, so somewhere do I write over a
limit...

That was lucky in that it lets you know the problem is probably in
this code. You might want to check out valrind and mudflap. I have
found both to be very useful.

Lets look at the code you corrected (edited down):

memset(p, ' ', X_BINS * Y_BINS);

/* check if a data point should be inserted, and in such case where */
int i = 0;
int ybin, xbin;
for (i=0; i<n; i++) {
if (x >= start_x && x <= slut_x &&
y >= start_y && y <= slut_y) {

/* where to put x */
xbin = (int) round( (x - start_x)/(slut_x - start_x)*X_BINS );
/* where to put y */
ybin = (int) round( (y - start_y)/(slut_y - start_y)*Y_BINS );

p[ybin*(X_BINS) + xbin] = '*';
}
}

Check your boundary conditions. x can == start_x. This makes xbin
== 0 and that is OK. x can be as large as slut_x and this makes

(x - start_x)/(slut_x - start_x)

exactly 1. Multiplying by X_BINS makes xbin == X_BINS and it must
range from 0 to X_BINS-1. The same problem occurs for ybin. Exactly
how you should solve this depends on exactly what you want to happen
at the boundaries. One option would be to remove the "if" and scale
every point but then reject those whose scaled int value is < 0 or >=
X_BINS. This relies on the scaled values being in the range of int
in all cases. Alternatively you could just protect the assignment with
a test xbin and ybin are both < X_BINS and Y_BINS respectively.

There are lots of other fixes, but the key is to ensure that the
scaled result is exactly in range. This is not helped bu the fact
that you are rounding the result. Sketch out on a grid exactly what
you want to happen at the edges.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,780
Messages
2,569,608
Members
45,252
Latest member
MeredithPl

Latest Threads

Top