2012-03-29 64 views
0

我有大量的包含整数的64x64矩阵的txt文件。 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`? 
} 
+0

你提供的代码片段,如果你删除了int指针声明,已经做了你想要的。它会第一次更新'fname'为''mat_1'',第二次更新'mat_2'等。 – 2012-03-29 12:03:58

+0

为什么有人会这样做?动态变量名称在脚本语言中已经很混乱了,编译语言中没有人需要它们! @JoachimPileborg:我认为他想动态地创建名为'mat_X'的变量 – ThiefMaster 2012-03-29 12:06:55

+0

如果它像@ThiefMaster所说的那样,那么不是不可能的。 C没有这样的功能,即使在图书馆也没有。 – 2012-03-29 12:12:42

回答

3

您不能在运行时创建变量名称。变量名称仅用于编译器,只有编译器才能知道并且不能即时生成。你需要的是一个数组。由于数据已经需要存储在一个数组中,所以需要为数组添加1维。

例如,如果在mat_1.txt数据是1个维阵列,可以有:

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); 
+0

我希望数据形式文件存储在变量mat_k,其中k是1,2,3,...问题是如何在周期中创建一个变量? – user1281071 2012-03-29 12:23:12

+1

@ user1281071看我的更新 – Shahbaz 2012-03-29 12:29:23

+0

谢谢!很棒:) – user1281071 2012-03-29 14:33:50

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会节省很少的空间,但其他方面是相同的。