krazibiosvn
krazibiosvn

Reputation: 85

Error in Code? [C]

I'm stuck in an infinite loop, for some reason the program doesn't terminate when \n is entered. Also the point of the code is to reverse the input, but I'm trying to do it using a pointer instead of an integer to keep track of the position in the array.

#define MSG_LENGTH 80

int main(void)
{
    char msg[MSG_LENGTH], *p;

    printf("Enter a message: ");

    for (p = msg; p < &msg[MSG_LENGTH];)
    {
        *p++ = getchar();

        if (*p == '\n')
            break;
    }

    printf("Reversal is: ");

    for (p--; p >= msg;)
        putchar(*p--);

    return 0;

}

Upvotes: 0

Views: 38

Answers (2)

Tarik
Tarik

Reputation: 11209

for (p = msg; p < &msg[MSG_LENGTH];)
{
    *p++ = getchar(); <-- Getting character in *p and incrementing p

    if (*p == '\n')   <-- Checking value of next character, not the one just read
        break;
}

Possible correction:

for (p = msg; p < &msg[MSG_LENGTH]; p+=sizeof(char))
{
    *p = getchar();

    if (*p == '\n')
        break;
}

Upvotes: 2

skrtbhtngr
skrtbhtngr

Reputation: 2251

Try this:

#define MSG_LENGTH 80

int main(void)
{
    char msg[MSG_LENGTH], *p;

    printf("Enter a message: ");

    for (p = msg; p < &msg[MSG_LENGTH];)
    {
        *p = getchar();
        if (*p == '\n')
            break;
        p++;
    }

    printf("Reversal is: ");

    for (p--; p >= msg;)
        putchar(*p--);

    return 0;

}

You were incrementing the p pointer before the break condition. So, even if *p was containing '\n', the check was being made after incrementing the pointer location.

Upvotes: 3

Related Questions