C 基于用户输入的每行字符缩进

C Characters per line indentation based on user input

我正在开发一个 C 项目,该项目将根据用户指定的每行字符数缩进一行。我在选择何时开始下一行时遇到了麻烦,因为它不能在两行之间拆分一个单词。 它应该工作的方式如下
1) 使用 wordPerLine 给它一个列表的副本检查可以进入该行的单词数
2) 添加单词直到达到该行的最大单词数
3) 达到最大字数后,换行继续,直到到达列表末尾。

它说 "Segment fault (Core dumped)"。如果您能给我一些帮助,我将不胜感激。

这是我的每行单词功能:

  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;
           }  
        }
     }
   }
}

Segment fault (Core dumped)

表示您试图读取程序分配的 RAM 之外的内存。这通常意味着您的程序中有一个指针,该指针已初始化(或未初始化)到程序分配的 RAM 之外的值,并且您已取消引用它(要求指针存储地址处的值)。

你的程序指针很少。让我们看看他们

currentPointer

用于

while(!isspace(currentPtr->data)&& currentPtr!=NULL) {

它会检查它是否是 NULL,但仅在它尝试获取数据并将其传递给 isspace(...) 之后才进行。

我认为您可能想在尝试取消引用之前检查 currentPtr 是否 NULL,就像这样

while(currentPtr!=NUll && !isspace(currentPtr->data)) {