Question regarding C loops
I'm not exactly sure why this isn't returning what it should be, perhaps one of you could help me out. I have the following for loop in C:
for (i=0; i<nrow; i++) {
dat[k]=l.0;
k++;
}
Now, you would think that this would set all values of dat
(of which there are nrow
values) to 1.0; Instead, it is being set to 0. The program compiles fine and everything goes smoothly. The memory is properly allocated and dat
is defined as a double
.
Is there a reason this is yielding 0? I'm guessing the 0 is coming from the initialization of the dat
variable (since I used calloc
for memory allocation, which supposedly initializes variables to 0 (but not always)).
EDIT: Please note that there is a specific reason (this is important) that I'm not defining it as dat[i]
. Additionally. k
was defined as an integer and was initialized to 0.
EDIT 2: Below is the entire code:
#include "stdio.h"
#include "stdlib.h"
#define NCH 81
// Generate swap-mode data for bonds for input.conf file
int main()
{
int i,j,k;
int **dat2;
double *dat;
int ns = 500;
int nrow = NCH*(ns-1);
dat = (double*) calloc(nrow, sizeof(double));
dat2 = (int**) calloc(nrow,sizeof(int*));
/*for (i=0; i<nrow; i++) {
dat2[i] = (int*) calloc(2, sizeof(int));
for (j=0; j<2; j++)
dat2[i][j] = 0;
}*/
k=0;
printf("\nBreakpoint\n");
/*for (i=0; i<81; i++) {
for (j=0; j<250; j++) {
dat[k] = j+1;
k++;
}
for (j=251; j>1; j++) {
dat[k] = j-1;
k++;
}
}*/
FILE *inp;
inp = fopen("input.out", "w");
for (i=0; i<nrow; i++) {
dat[k]=1.0;
k++;
}
//fprintf(inp, "%lf\n", dat[i]);
printf("%d", dat[nrow]);
printf("\nDone\n");
fclose(i开发者_开发知识库np);
return 0;
}
Thanks! Amit
printf("%d", dat[nrow]);
is not valid, because the nrow'th element of dat doesn't exist.
Are you sure you are starting 'k' at zero?
In the sample you posted you are using l not 1 - is this just a typo?
for (i=0; i<nrow; i++) {
dat[k]=1.0;
k++;
}
That should work.
Two things:
I'm assuming the l.0 is a type and your l is actually a 1.
Secondly, why are you using k in your for loop instead of using i? Try using this instead:
for (i=0; i<nrow; i++) {
dat[i]=1.0;
}
Either this works your compiler/hardware is bugged.
k = 0;
for (i=0; i < nrow; i++) {
dat[k++] = 1.0f;
}
printf("%d, %d", dat[0], dat[nrow - 1]);
when you printf("%d", dat[nrow])
, dat[nrow]
has not been set to 1. In the for loop the condition is i < nrow
so it's before it. You need i <= nrow
.
精彩评论