[英]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:
我在C中有以下for循环:
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; 现在,您会认为这会将
dat
所有值(其中有nrow
值)设置为1.0; Instead, it is being set to 0. The program compiles fine and everything goes smoothly. 而是将其设置为0。程序可以正常编译,并且一切运行顺利。 The memory is properly allocated and
dat
is defined as a double
. 内存已正确分配,并且
dat
定义为double
。
Is there a reason this is yielding 0? 是否有原因会产生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)). 我猜是0来自于
dat
变量的初始化(因为我使用calloc
进行内存分配,因此可以将变量初始化为0(但并非总是如此))。
EDIT: Please note that there is a specific reason (this is important) that I'm not defining it as dat[i]
. 编辑:请注意,有一个特定的原因(这很重要),我没有将其定义为
dat[i]
。 Additionally. 另外。
k
was defined as an integer and was initialized to 0. k
定义为整数,并初始化为0。
EDIT 2: Below is the entire code: 编辑2:以下是完整的代码:
#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(inp);
return 0;
}
Thanks! 谢谢! Amit
阿米特
printf("%d", dat[nrow]);
无效,因为dat的第nrow个元素不存在。
Are you sure you are starting 'k' at zero? 您确定要从零开始以“ k”开头吗?
In the sample you posted you are using l not 1 - is this just a typo? 在您发布的样本中,您使用的不是l-是错字吗?
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. 我假设l.0是类型,而您的l实际上是1。
Secondly, why are you using k in your for loop instead of using i? 其次,为什么在for循环中使用k而不是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. 当您
printf("%d", dat[nrow])
, dat[nrow]
尚未设置为1。在for循环中,条件是i < nrow
所以它在它之前。 You need i <= nrow
. 你需要
i <= nrow
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.