是否可以使用循环来声明变量?

时间:2012-03-29 12:00:21

标签: c

我有大量的txt文件,其中包含由整数组成的64x64矩阵。 txt文件的名称如下:

mat_1.txt,mat_2.txt,mat_3.txt,mat_4.txt,....,mat_n.txt。

我必须创建一个变量,在主机和设备上分配空间,读取txt文件并复制到设备。是否可以在一个循环中完成所有操作?

我知道如何使用sprintf创建字符串,但不知道如何使用此字符串来声明变量。

char fname[10]; 
for( int k=1; k<=n; k++ )
{
    sprintf( fname, "mat_%d", k );
    int *fname;    // how to say to compiler that insted of `fname` there 
                   // should be `mat_1` and in next cycle `mat_2`?
}

2 个答案:

答案 0 :(得分:3)

您无法在运行时创建变量名称。变量名用于编译器,只有编译器才能知道,无法动态生成。

你需要的是一个阵列。由于数据已经需要存储在数组中,因此需要为数组添加1维。

例如,如果mat_1.txt中的数据是一维数组,则可以:

int **mat;                        // 2D array
int k;
mat = malloc(n * sizeof(*mat));   // get an array of pointers (add error checking)
for (k = 1; k <= n; ++k)
{
    char fname[20]; 
    FILE *fin;
    sprintf(fname, "mat_%d.txt", k);
    fin = fopen(fname, "r");
    if (fin == NULL)
        /* Handle failure */
    /* read number of items */
    mat[k-1] = malloc(number of items * sizeof(*mat[k-1]));  // allocate an array for each file
    /* read data of file and put in mat[k-1] */
    fclose(fin);
}
/* At this point, data of file mat_i.txt is in array mat[i-1] */
/* When you are done, you need to free the allocated memory: */
for (k = 0; k < n; ++k)
    free(mat[k]);
free(mat);

答案 1 :(得分:1)

你在用什么电脑?

int的64x64数组,其中int是4个字节,是16,386字节的数组,22,500个文件,1个矩阵/文件将是368,640,000字节。

在我5岁的笔记本电脑上运行正常:

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


#define MAX_FILES (22500)
#define MAX_J (64)
#define MAX_K (64)

int a[MAX_FILES][MAX_J][MAX_K];
const char namefmt[] = "mat_%d";

int main (int argc, const char * argv[]) {
    char fname[strlen(namefmt)+10+1];  // an int has 10 or less digits
    for (int fileNumber=0; fileNumber<MAX_FILES; ++fileNumber) {
        sprintf(fname, namefmt, fileNumber);
        FILE* fp = fopen(fname, "r");
        if (fp == NULL) {
            fprintf(stderr, "Error, can't open file %s\n", fname);
            exit(1);
        }
        for (int j=0; j<MAX_J; ++j) {
            for (int k=0; k<MAX_K; ++k) {
                //... read the value
            }
        }
        fclose(fp);
    }
    return 0;
}

在运行具有虚拟内存的操作系统和足够的交换空间的现代计算机上,它应该可以正常工作(尽管可能会变得非常缓慢)。将其声明为数组,而不是使用malloc将节省极少量的空间,但在其他方面是相同的。

相关问题