[英]A string is suddenly losing its value inside a function
I have code which should read the filenames from a file, open those, and do some calculations. 我有应该从文件中读取文件名,打开它们并进行一些计算的代码。 Those files contain columns of data.
这些文件包含数据列。 I have declared arrays to read in the data.
我已经声明要读取数据的数组。 The strings containing file names are behaving in an erratic manner when I initialise the arrays before reading in. If the initialisation is removed, the problem is solved.
当我在读入之前初始化数组时,包含文件名的字符串以一种不稳定的方式运行。如果删除了初始化,则可以解决问题。
The erratic behaviour is: the string declared first isn't remaining in the memory. 不稳定的行为是:首先声明的字符串没有保留在内存中。 In the code, if I declare
d[90]
first, then a print statement at a later time does not print the previously saved value. 在代码中,如果我先声明
d[90]
,则稍后的一条print语句不会打印先前保存的值。 What could be the cause? 可能是什么原因?
Here is the code: 这是代码:
#include<stdio.h>
#include<math.h>
main()
{
FILE *data,*model,*filenames;
int i,imax,j,k,l;
float fd[1000],fm[1000],td[1000],tm[1000];
float a;
char d[90],m[90];
k=1;
l=0;
filenames=fopen("filenames.dat","r");
while(fscanf(filenames,"%s %s",d,m)!=EOF)
{
printf("model: %s\ndata: %s\n",m,d);
for(i=1;i<=1000;i++)
{
fd[i]=0;
fm[i]=0;
td[i]=0;
tm[i]=0;
}
printf("datafile name: %s\n",d);
printf("modelfile name: %s\n",m);
data=fopen(d,"r");
for(i=1;i<=1000;i++)
if(fscanf(data,"%f %f %f %f",&td[i],&fd[i],&a,&a)!=EOF)
k++;
else
break;
fclose(data);
printf("modelfile name: %s\n",m);
model=fopen(m,"r");
for(i=1;i<=1000;i++)
if(fscanf(model,"%f %f %f %f %f %f",&tm[i],&fm[i],&a,&a,&a,&a)!=EOF)
l++;
else
break;
fclose(model);
}
}
In your code, with a definition like float fd[1000]
and so on, using the for
loop like 在代码中,与像一个定义
float fd[1000]
等,使用for
等环
for(i=1;i<=1000;i++)
{
fd[i]=0;
fm[i]=0;
td[i]=0;
tm[i]=0;
}
creates off-by-one error and hence cause undefined behaviour , as essentially, you're trying to access past the allocated memory. 会产生一个错误,并因此导致未定义的行为 ,从本质上讲,您正在尝试访问已分配的内存。
As C
uses 0
-based indexing, you should be using index from 0
to (size-1)
for an array with size
elements. 由于
C
使用基于0
的索引,因此对于具有size
元素的数组,应使用从0
到(size-1)
索引。
Also, always check the return value of fopen()
against NULL
to ensure it's success. 另外,请始终针对
NULL
检查fopen()
的返回值,以确保成功。 In case fopen()
failed, using the returned pointer will again invoke UB. 如果
fopen()
失败,则使用返回的指针将再次调用UB。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.