2012-12-09 92 views
2

我正在逐行閱讀文本文件到二維數組中。我想連接字符數組,所以我有一個長字符數組。我遇到了麻煩,我可以讓它與兩個char數組一起工作,但是當我嘗試去做很多時,我會出錯。C與2D字符數組的連接

目前的字符數組是這樣的:

AGCTTTTCATTC 

我想是這樣的:

AGCTTTTCATTCAGCTTTTCATTC 

我已經inlcuded我的一些代碼。

int counter = 0; 
fid = fopen("dna.fna","r"); 
while(fgets(line, sizeof(line), fid) != NULL && counter!=66283) { 
    if (strlen(line)==70) { 
     strcpy(dna[counter], line);   
    counter++; 
    } 
} 
int dnaSize = 6628; 
//Concatenating the DNA into a single char array. 
int i; 
char DNA[dnaSize]; 
for(i = 0; i<66283;i++){ 
    strcpy(DNA[i],dna[i]); 
    strcat(DNA[i+1],dna[i+1]); 
} 
+0

-1很抱歉,但我必須要平衡這個問題了的得分。它在我看來缺乏研究努力。我想如果你閱讀了'strcpy'和'strcat',你可以自己做更多。附:很高興看到'dna'的定義,因爲這可能會使用第一個'strcpy'錯誤。 – weston

回答

1

您需要循環僅達< counter 然後,你複製或串聯?你只需要做一個或另一個。

我建議只在循環中使用strcat,但初始化DNA。

char DNA[dnaSize] = ""; //initalise so safe to pass to strcat 
for(i = 0; i<counter;i++) 
{ 
    strcat(DNA,dna[i]); //no need for indexer to DNA 
} 

此外,您還需要考慮你的兩個數組的大小。我相信(希望)dna是一個數組char的數組。如果是這樣,我想它僅在第一維方面就是66283。所以它不適合DNA6628長),即使每行都是1個字符長度。

下面是關於如何準確地分配內存適量的想法:

#define MAXLINELENGTH (70) 
#define MAXDNALINES (66283) 

//don't copy this line, it will not work because of the sizes involved (over 4MB) 
//it will likely stack overflow 
//just do what you are currently doing as long as it's a 2-d array. 
char dna[MAXDNALINES][MAXLINELENGTH + 1]; 

int counter = 0; 
int totalSize = 0; 
fid = fopen("dna.fna","r"); 
while(fgets(line, sizeof(line), fid) != NULL && counter!=MAXDNALINES) { 
    const int lineLength = strlen(line); 
    if (lineLength==MAXLINELENGTH) { 
     strcpy(dna[counter], line);   
     counter++; 
     totalSize += lineLength; 
    } 
} 

//Concatenating the DNA into a single char array (of exactly the right length) 
int i; 
char *DNA = malloc(totalSize+1); // the + 1 is for the final null, and putting on heap so don't SO 
DNA[0] = '\0'; //the initial null is so that the first strcat works 
for(i = 0; i<counter;i++){ 
    strcat(DNA,dna[i]); 
} 

//do work with DNA here 

//finally free it 
free(DNA);