C++ realloc内存可以';t在C+中不能正常工作+;
当我执行cout Seka时,例如,如果dummyLine=Acacata Seka有问题。我对动态数组使用temp,因为在编写代码之后,seka[lenA]编译器说数组的维数必须确定C++ realloc内存可以';t在C+中不能正常工作+;,c++,c,C++,C,当我执行cout Seka时,例如,如果dummyLine=Acacata Seka有问题。我对动态数组使用temp,因为在编写代码之后,seka[lenA]编译器说数组的维数必须确定 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_FAILU
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();
char*seka=NULL;
char*temp=NULL;
int-lenA=0;
文件a.open(“d:\\str1.fa”);
if(fileA==NULL){
perror(“打开'str1.fa'时出错”);
退出(退出失败);
}
弦线;
getline(fileA,dummyLine);
while(getline(fileA,dummyLine)){
lenA=lenA+(dummyLine.length());
temp=(char*)realloc(seka,lenA*sizeof(char));
如果(温度!=NULL){
seqA=温度;
对于(int i=0;i而言,问题在于您没有在seka
的末尾添加空字符
realloc
将给您一个指向未初始化内存的指针。然后您从dummyLine
复制每个字符,但之后只有随机内存。请确保在seka
的末尾添加一个空字符,以使其成为有效的C字符串
考虑到这一点,您需要在分配中添加一个额外的字符,其中空字符可以位于temp=(char*)realloc(seka,(lenA+1)*sizeof(char));
seka[lenA-1]='\0';
out问题在于您没有在seka
的末尾添加空字符
realloc
将给您一个指向未初始化内存的指针。然后您从dummyLine
复制每个字符,但之后只有随机内存。请确保在seka
的末尾添加一个空字符,以使其成为有效的C字符串
考虑到这一点,您需要在分配中添加一个额外的字符,其中空字符可以位于temp=(char*)realloc(seka,(lenA+1)*sizeof(char));
seka[lenA-1]='\0';
out我对这段代码的理解是,您试图读取文件中的所有行,并将它们连接到单个缓冲区中。为此,您应该使用另一个字符串对象。类似于:-
string dummyLine;
string fileContents;
getline(fileA, dummyLine);
while(getline(fileA, dummyLine)) {
fileContents += dummyLine;
}
这将让std::string完成所有繁重的工作,这样您就不必这么做了。也要短得多。我对这段代码的理解是,您试图读取文件中的所有行,并将它们连接到一个缓冲区中。要做到这一点,您应该使用另一个string对象。类似于:-
string dummyLine;
string fileContents;
getline(fileA, dummyLine);
while(getline(fileA, dummyLine)) {
fileContents += dummyLine;
}
这将让std::string完成所有繁重的工作,这样您就不必这么做了。而且要短得多