c - 无法在 while 循环外保留数组

标签 c embedded signal-processing blackfin

我目前正在处理下面的 C 代码。我需要在 fclose 之后访问 while 循环之外的数组。似乎每次我运行 blackfin ADSP 内核都会崩溃。我将需要它进一步执行 FFT。请帮忙!

#include <stdlib.h>
#include <stdio.h>
#include <flt2fr.h>
#include <fract_math.h>
#include <math_bf.h>
#include <complex.h>
#include <filter.h>

int main() 
{
    int n = 1024;
    long int dat1[n];
    FILE *file1;
    fract16 *m;
    int i;

    // file1 open and read the values
    file1 = fopen("0.dat", "r");
    if (file1 == NULL) {
       printf("I couldn't open 0.dat for reading.\n");
       exit(0);
    }

    while (!feof(file1)) {
        fgets(dat1, n, file1);
        m = malloc(sizeof(fract16) * n);
        for (i = 0; i < n; i++) {
            sscanf(dat1, "%f", &m[i]); //getting error here
        }
    }

    fclose(file1);
    printf("%lf\n", m);
    return 0;
}

好的,谢谢大家指正我的错误,但是问题还是没有解决。我能够在内部打印所有值,但在循环外它只打印数据集的最后一个值,是否有任何精确的解决方案?我用谷歌搜索了几个小时,但还没有成功。 代码如下>

#include <stdlib.h>
#include <stdio.h>
#include <flt2fr.h>
#include<fract_math.h>
#include <math_bf.h>
#include <complex.h>
#include <filter.h>
int main()
{
    int n = 1024;
    long int dat1[n];
    FILE *file1;
    fract16 *m;

    file1 = fopen("0.dat", "r");
      if (file1 == NULL) {
         printf("I couldn't open 0.dat for reading.\n");
         exit(0);
      }

    while( !feof(file1))
    {

       fgets(dat1,n,file1);
       sscanf(dat1, "%f", &m);
       printf("%f\n",m); //Prints all elements in the 1st column of the  array, 0.dat is a nx2 matrix
    }
    fclose(file1);
}

最佳答案

您可以在读取文件之前为缓冲区分配内存,在 while 循环之外。然后每次在读入缓冲区之前,只需使用 memset 并将缓冲区设置为所有空字符。

此外,尝试使用 fread 直接读入缓冲区而不是 fgets

关于c - 无法在 while 循环外保留数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40935956/

相关文章:

c - UNIX 编程 - C 中的信号量、共享内存

c - 通过内存访问跟踪文件确定缓存读/写/命中/未命中

linux - 在嵌入式 Linux 上安全写入紧凑型闪存

c++ - 在一定秒数内更改缓冲区大小

c - 如何在一个循环中打印所有id名称?

c - 将与输入 vector 相同的输出传递给 GEMV 以实现破坏性矩阵应用是否安全?

c++ - 存储函数指针供以后使用

c - 用C语言设计主站(PC或ARM板)和从站(微处理器)之间简单而强大的串行协议(protocol)

filtering - 在 Verilog 中实现 FIR 滤波器

c - arm_rfft_init_q31 : how is the cfft member initialized?