gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 04:31:12 25 4
gpt4 key购买 nike

我正在开发一个 C 项目,该项目将根据用户指定的每行字符数缩进一行。我在选择何时开始下一行时遇到了麻烦,因为它不能在两行之间拆分一个单词。它应该工作的方式如下
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;
}
}
}
}
}

最佳答案

Segment fault (Core dumped)

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

你的程序只有很少的指针。让我们看看它们

currentPointer

用于

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

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

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

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

关于C 基于用户输入的每行字符缩进,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36076156/

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