Jonathan Groß wrote, On 05/02/07 15:28:
Hi everybody,
in the sample below my programm gives a "Bus error" on the marked line.
I don't get it why that happens. I followed the instructions in the C-FAQ.
Not very well though.
#include <math.h>
#include <stdlib.h>
#define dim 2
#define length 3
Macros are traditionally all upper case, going against this convention
makes it harder for those used to it, i.e. most C programmers.
int main (int argc, const char * argv[]) {
int i,j;
int volume=(int)pow(length,dim);
You don't need the cast, it will behave exactly the same without it.
Also, without a good reason I'm not convinced that using a floating
point function is the best way to generate an array size.
int **nbrs = (int **) malloc(volume * sizeof(int *));
Does the C FAQ really use all these horrible and needless casts.
<check/>
No, it doesn't. Why do the extra typing when it is just more to get
wrong and can even hide two different problems. Also, as the C FAQ notes
in a footnote, there is a better way to use sizeof.
int **nbrs = malloc(volume * sizeof *nbrs);
About 10 fewer characters to type and less error prone.
Also, as the FAQ notes, you should check the return value of malloc.
for (i=0; i<volume; i++)
*(nbrs+i) = (int *) malloc(2*dim * sizeof(int));
Same comments as before, aditionally I would use array is easier to read
(in my opinion) in this case.
nbrs[i] = malloc(2*dim * sizeof *nbrs[i]);
for (i=0;i<volume;i++)
for(j=0;j<(2*dim);j++) {
*(nbrs+i)=i;
*(*(nbrs+i)+j)=j; //here is the problem
Again, array notation makes it easier to read.
nbrs[i]=i;
nbrs[i][j]=j;
Now look at the first of these two lines and compare it to the loop
allocating the space for the rows. You should see that you are
overwriting all those pointers you were so careful to allocate. Your
compiler should even have complained about the assignment "*(nbrs+i)=i"
to let you know it is a problem. Whether the problem is that you want
something other than a 2D array or whether you don't understand pointers
to pointers or what is hard to say at this point.
}
for (i=0; i<volume; i++)
printf("%d\n", nbrs[i]);
This loop also does not make sense.
return 0;
}
--
Flash Gordon