2012-03-29 84 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會節省很少的空間,但其他方面是相同的。