gpt4 book ai didi

解析章节时的Coredump

转载 作者:行者123 更新时间:2023-12-02 00:37:10 25 4
gpt4 key购买 nike

我正在做一项阅读一本书的家庭作业。首先,读入一行并使指针指向该行。然后一个段落函数读取行并将它们的地址存储到一个指针数组中。现在,我正在阅读一章(下一行被打破的段落)。它应该调用 get_paragraph() 并存储段落的地址,直到到达新的章节。

新章节是书中唯一一次第一个字符不是空格的情况。我认为这是我的代码有问题。到目前为止的所有功能都可以工作。我希望我已经提供了足够的信息。代码编译但启动时核心转储。

我是一名学生,正在学习,所以请善待。谢谢。

char*** get_chapter(FILE * infile){

int i=0;

char **chapter[10000];//an array of pointers
// Populate the array
while(chapter[i]=get_paragraph(infile)) { //get address store into array
if(!isspace(**chapter[0])){ //check to see if it is a new chapter<---problem line?
// save paragraph not used in chapter using static to put into next chapter
break;
}
i++;//increment array
}
//add the null
chapter[++i]='\0';//put a null at the end to signify end of array
//Malloc the pointer
char**(*chap) = malloc(i * sizeof(*chap));//malloc space
//Copy the array to the pointer
i=0;//reset address
while(chapter[i]){//while there are addresses in chapter
chap[i] = chapter[i++];//change addresses into chap
}
chap[i]='\0';//null to signify end of chapter
//Return the pointer
return(chap);//return pointer to array
}

对于那些宁愿看到没有评论的人:

 char*** get_chapter(FILE * infile){

int i=0;

char **chapter[10000];
while(chapter[i]=get_paragraph(infile)) {
if(!isspace(**chapter[0])){
break;
}
i++;
}
chapter[++i]='\0';
char**(*chap) = malloc(i * sizeof(*chap));//malloc space
i=0;
while(chapter[i]){
chap[i] = chapter[i++];
}
chap[i]='\0';
return(chap);
}

最佳答案

内联评论。

char*** get_chapter(FILE * infile) {
int i=0;

// This is a zero length array!
// (The comma operator returns its right-hand value.)
// Trying to modify any element here can cause havoc.
char **chapter[10,000];

while(chapter[i]=get_paragraph(infile)) {
// Do I read this right? I translate it as "if the first character of
// the first line of the first paragraph is not whitespace, we're done."
// Not the paragraph just read in -- the first paragraph. So this will exit
// immediately or else loop forever and walk off the end of the array
// of paragraphs. I think you mean **chapter[i] here.
if(!isspace(**chapter[0])){
break;
}
i++;
}

// Using pre-increment here means you leave one item in the array uninitialized
// which can also cause a fault later on. Use post-increment instead.
// Also '\0' here is the wrong sort of zero; I think you need NULL instead.
chapter[++i]='\0';

char**(*chap) = malloc(i * sizeof(*chap));
i=0;
while(chapter[i]) {
// This statement looks ambiguous to me. Referencing a variable twice and
// incrementing it in the same statement? You may end up with an off-by-one error.
chap[i] = chapter[i++];
}

// Wrong flavor of zero again.
chap[i]='\0';
return(chap);
}

关于解析章节时的Coredump,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4151917/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com