Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a problem with this code which is supposed to make a reverse sentence.

Example:

Input

Hi my name is Robert

Output

Robert is name my Hi

#include <stdio.h>

#define LEN 50

int main(void)
{
char input, terminator = 0, sentence[LEN+1] = {0};
int i, j, last_space = LEN + 1, posc=0;;
int pos[]={0};

printf("
Enter a sentence: ");
for (i = 0; (input = getchar()) != '
'; i++)
{
    if(input== ' '){
        pos[posc]=i;
        posc++;
    }
    if (input == '.' || input == '?' || input == '!')
    {
        last_space = i;
        terminator = input;
        break;
    }

    sentence[i] = input;
}

if (terminator == 0)
{
    printf("Sentence needs a terminating character. (./?/!)

");
    return 0;
}

printf("Reversal of sentence: ");
for (i = last_space; i > 0; i--)
{
    if (sentence[i] == ' ')
    {
        for (j = i + 1; j != last_space; j++)
        {
            putchar(sentence[j]);
        }
        last_space = i;
        putchar(sentence[i]);
    }
}
while (sentence[i] != '' && sentence[i] != ' ')
{
    putchar(sentence[i++]);
}
printf("%c

", terminator);
for(int i=sizeof(pos)-1; i>0; i--){
    printf("%.*s", sentence[pos[i-1]], sentence[pos[i]]);
}
printf("%c

", terminator);
return 1;
}

This keeps crashing because of the method at the bottom here:

printf("%c

", terminator);
for(int i=sizeof(pos)-1; i>0; i--){
    printf("%.*s", sentence[pos[i-1]], sentence[pos[i]]);
}
printf("%c

", terminator);
return 1;
}

Can someone help me fix this snippet of code for me so that both methods work when run? Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
124 views
Welcome To Ask or Share your Answers For Others

1 Answer

The array of size 1 is created by the line:

int pos[]={0};

And later you are accessing over the array's limit here:

if(input== ' '){
    pos[posc]=i;
    posc++;
}

The behaviour is undefined after that. The same mistake presents in the code you've mentioned due to sizeof returns the size in bytes, not just amount of elements.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...