繁体   English   中英

printf的分段错误

[英]Segmentation fault at a printf

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

它应该起作用的方式如下:

输入:这是一个程序

输出:程序a是这个

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

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不会随时相同。 因此,只有您遇到了分段错误错误。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM