Reputation: 11
#include <stdio.h>
#include <stdlib.h>
int main(void) {
double** F = (double**) malloc(4097 * sizeof(double*));;
int flops = 0;
int i, j, k;
double r;
for (i=0; i<4097; i++) {
F[i] = (double*) malloc(4097*sizeof(double));
}
// insert code to initialize array elements to random values between 1.0 and 2.0
for (i=0; i<4097; i++) {
for (j=0; j<4097; j++) {
r = (double)rand()/(double)(RAND_MAX/2.0);
F[i][j] = r;
printf("%f %f\n", r, F[i,j]);
}
}
}
I am trying to generate random numbers and store them into a 4097 x 4097 array but when the above code is run the array is not updated.
Upvotes: 1
Views: 100
Reputation: 271
Why are you using the comma operator F[i,j]
? The array populates correctly... just replace this with F[i][j]
to verify.
Also, free your memory.
Upvotes: 0
Reputation: 121397
This line
printf("%f %f\n", r, F[i,j]);
should be
printf("%f %f\n", r, F[i][j]);
However, the reason it's a valid syntax is because of the comma operator. Comma operator evaluates its operands and yields only the last operand's value. So,
printf("%f %f\n", r, F[i,j]);
is equivalent to
printf("%f %f\n", r, F[j]);
However, this has a problem. F[j]
is of type double *
whereas %f
expects a double
. GCC warns:
warning: format ‘%f’ expects argument of type ‘double’, but argument 3
has type ‘double *’ [-Wformat=]
Increasing your compiler warning levels would help catch these.
Upvotes: 1