我正在处理一个C项目,该项目将根据用户指定的每行字符数缩进一行。我在如何选择何时开始下一行时遇到问题,因为它无法在2行之间分解单词。
它的工作方式如下
1)使用wordPerLine检查可以进入该行的单词数量,并为其提供列表的副本
2)添加单词,直到达到该行的最大单词为止
3)在达到最大单词后,开始一个新行并继续,直到到达列表末尾。
它说"段故障(核心转储)"。如果有任何帮助你可以给我,我非常感激。
这是我的每行功能:
int wordPerLine(int size,LISTNODEPTR temp){
int chars=0;
int words=0;
int spaces=0;
while(temp!=NULL && (chars+spaces)<size){
if(!isspace(temp->data)) {
chars++;
temp=temp->nextPtr;
} else {
words++;
chars++;
spaces=words-1;
temp=temp->nextPtr;
}
}
return words;
}
我的列表结构:
struct listNode { /* self-referential structure */
char data;
struct listNode *nextPtr;
};
打印功能我试图将所有内容与
放在一起void printList(LISTNODEPTR currentPtr, int spaces)
{
//Temp variable to avoid moving the actual pointer in the length function
LISTNODEPTR temp = currentPtr;
int x=0;
int remaining=0;
int chars=0;
int wordsAvail=0;
int wordsUsed=0;
if (currentPtr == NULL)
printf("Empty String.\n\n");
else {
//Checks if the list is at the end and exits if TRUE
while(currentPtr!=NULL){
wordsAvail=wordsPerLine(spaces,temp);
for(wordsUsed=0; wordsUsed<=wordsAvail;wordsUsed++) {
while(!isspace(currentPtr->data)&& currentPtr!=NULL) {
printf("%c",currentPtr->data);
currentPtr=currentPtr->nextPtr;
temp=currentPtr;
}
wordsUsed++;
printf(" ");
while(isspace(currentPtr->data)&& currentPtr!=NULL) {
currentPtr=currentPtr->nextPtr;
temp=currentPtr;
}
}
}
}
}
答案 0 :(得分:0)
段故障(核心转储)
表示您试图读取程序分配的RAM之外的内存。这通常意味着您的程序中有一个指针,该指针初始化(或未初始化)到程序的已分配RAM之外的值,并且您已取消引用它(要求指针存储的地址处的值)。
你的程序只有很少的指针。我们来看看它们
currentPointer
用于
while(!isspace(currentPtr->data)&& currentPtr!=NULL) {
检查它是否为NULL
,但仅在它尝试获取数据并将其传递给isspace(...)
之后。
我想你可能想要在尝试取消引用之前检查currentPtr是否为NULL
,如此
while(currentPtr!=NUll && !isspace(currentPtr->data)) {