0

cout seqA を実行すると、たとえば、dummyLine=ACACACTA seqA に問題がある場合。このコードの後に​​ seqA[lenA] コンパイラーが配列の次元を決定する必要があると言ったため、動的配列に temp を使用します。

char *seqA=NULL;
char *temp=NULL;
int lenA = 0;

fileA.open("d:\\str1.fa");
if(fileA == NULL) {
    perror ("Error opening 'str1.fa'\n");
    exit(EXIT_FAILURE);
}

string dummyLine;
getline(fileA, dummyLine);

while(getline(fileA, dummyLine)) {
    lenA=lenA+(dummyLine.length());
    temp=(char*)realloc(seqA,lenA*sizeof(char));
    if (temp!=NULL) {
        seqA=temp;
        for (int i=0; i<(dummyLine.length()); i++)
        {
            seqA[lenA-dummyLine.length()+i]=dummyLine[i];
        }
    }
    else {
        free (seqA);
        puts ("Error (re)allocating memory");
        exit (1);
    }
}

cout<<"Length seqA is: "<<lenA<<endl;
cout<<seqA<<endl;
fileA.close();

出力の写真: ここに画像の説明を入力

4

2 に答える 2

2

問題は、の最後にヌル文字を置かないことですseqA

realloc初期化されていないメモリへのポインタを提供します。次に、各文字をコピーしますdummyLineが、その後はランダムなメモリしかありません。seqA有効な C 文字列にするために、末尾にヌル文字を追加してください。

そのことを念頭に置いて、null char が座ることができる割り当てに余分な文字を追加する必要がありますtemp=(char*)realloc(seqA,(lenA+1)*sizeof(char));

seqA[lenA-1] = '\0';
out<<seqA<<endl;
于 2013-05-05T06:52:05.830 に答える