gpt4 book ai didi

c - printf 中的段错误

转载 作者:太空宇宙 更新时间:2023-11-04 04:33:55 24 4
gpt4 key购买 nike

我目前正在学习 C,并且正在开发一个程序,该程序使用一维数组颠倒句子中的单词顺序。

它的运作方式应该是这样的:

输入:这是一个程序

输出:程序a是这个

但是当我尝试运行它时,我收到一条错误消息“段错误”,我认为这意味着程序正在尝试访问它不应该访问的内存。

GDB 告诉我问题出在循环中的 printf

这是我的代码:

#include <stdio.h>
#define N 99

//initialize i at 1 to leave space in beginning
int i=1;

//j is for counting charachters of individual words
int j=0;

//initailize char array with spaces
char array[N]={' '};


int main(void)
{


printf("Enter a sentence ended by a [. or ! or ?]: ");


//enter sentence charachter by charachter into an array. end at terminator.
for (i=1 ; ; i++ )
{
array[i]=getchar();
if (array[i]=='.' || array[i]=='!' || array[i]=='?')
{
break;
}

}


//begin loop.
for ( ; array[i] != array[0] ; )
{
//note current position of i into j. j is end marker.
j=i;

//search backward from j for the beginning of last word (after a space).
for (i=j ; array[i]!= ' ' ; i--)
{

}
i++; //move to beginning of word

//print word to end counting places moved. stop at j.
for ( ; i!=j ; i++)
{
printf("%c", array[i]);
j++; //increment j to determine number of charachters.
}


//move back the same amount of places moved.
for ( ; j!=0 ; j--)
{
i--;
}
//i--; //move back once more

//update j to new position.

//start loop again.
}


return 0;
}

最佳答案

for ( ; i!=j ; i++)
{
printf("%c", array[i]);
j++; //increment j to determine number of charachters.
}

在这个循环中就是无限循环。因为你同时增加了 i 和 j。 所以,在这里 j 和 i 不会在任何时候变得相同。 因此,只有您遇到段错误。

关于c - printf 中的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33161783/

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