fscanf并分配2D数组

时间:2014-07-19 15:07:43

标签: c arrays

为什么以下代码没有为2D数组元素赋值?它从文件中读取数据;每次为x分配正确的值,但是2D数组X是零,它是初始化时的值。 malloc分配的数组,我正在使用gcc(GNU)。这是代码的一部分

#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<omp.h>

#define N_mon     868// number of monomer per chain.
#define N_seg     N_mon/segm //number of segments per chain.
#define N_f2      511 // number of frames after.  
#define s1        500 
#define s2        1000
int main (void)
{
    FILE *finput1, *foutput1;
    char line1[140];
    float x=0., y=0., z=0., corang[N_f2]={0.0} ;
    int i=0, kk=0, ll=0, pid1=0, count=0, tot_count1=0, dt=0, cnt[N_f2]={0}, t=0;
    float **X;

    X=(float**)malloc(N_f2*sizeof(float*));
    for (i=0; i< N_f2; i++)
    {
        X[i]=(float*)malloc(N_mon*sizeof(float));
    }

    if ((finput1=fopen("./Stiff.vtf","r")) == NULL)
    {
         printf("Error: iutput file .vtf cannot be opened");
         return 0;
    }

    if ((foutput1=fopen("./msdr.dat","w")) == NULL)
    {
        printf("Error: output file msdr.dat cannot be opened");
        return 0;
    }

    for (ll=0; ll<N_f2; ll++)
        for (kk=0; kk<N_mon; kk++)
            X[ll][kk]=0.0;

    while(fgets(line1,120,finput1))
    {
        pid1=0;
        if(strncmp(line1,"timestep",8)==0)
        {
            if ( (count>=s1) && (count<s2) )
            {
                while (fscanf(finput1, "%f %f %f", &x,&y,&z) > 0)
                {
                    X[tot_count1][pid1]=x;
                    printf("x=%f and X=%f \n", x, X[tot_count1][pid1]);
                    pid1++;  
                }
                tot_count1++;
            }
            count++;
        } // if timestep
    } //while loop
// MSDs
    for (t=0;t<tot_count1-1;t++)
    {
        for (dt=1;(t+dt)<tot_count1;dt++)
        {
            cnt[dt]++;  // number of origins for interval length dt  
            for (i=0;i<N_mon;i++)
            {
                corang[dt]  += (X[t+dt][i] - X[t][i])*(X[t+dt][i] - X[t][i]);
            }
        }
    }

  //now msdx.....
    for (t=0;t<tot_count1-1;t++)
    {
        corang[dt]  /= cnt[t]?(N_mon*cnt[t]):1;
        fprintf(foutput1,"%d  %f \n",t, corang[dt]);
    }

    fclose(finput1);
    fclose(foutput1);

    for (i=0; i<N_f2; i++) free((void*)X[i]);
        free((void*)X);

    return (0);
}

0 个答案:

没有答案