简体   繁体   中英

Segmentation fault at a printf

I'm currently learning C and I'm working on a program that reverses the order of words in a sentence using 1D arrays.

The way it is supposed to function is as follows:

Input: this is a program

Output: program a is this

But when I try to run it I get an error saying "Segmentation fault" which I assume means the program is trying to access memory that it shouldn't.

GDB told me the problem was at the printf in my loop

Here's my code:

#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.
}

In this loop is infinite loop. Because you are increasing i and j both. So, in here the j and i does not become same in any time. So, only you are getting a segmentation fault error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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