0

So I'm trying to reverse an array of strings. The code is working but the issues are:

  1. After the last input I have to enter an extra char (any char will do) and press enter in order for the code to execute.

  2. That it prints 2 random char or ?? before the output. Can anyone please explain why it's printing those ??...

code:

#include <stdio.h>

int     main(void)
{
    int     tot_books;
    int     i;
    int     j;

    scanf("%d\n", &tot_books);

    char    titles[tot_books][101];

    i = 0;
    while (i < tot_books)
    {
        scanf("%[^\n]\n", titles[i]);
        i++;
    }

    while (tot_books >= 0)
    {
        printf("%s\n", titles[tot_books]);
        tot_books--;
    }
    return (0);
}

output:

7
Germinal
Le petit prince
Le meilleur des mondes
L'ecume des jours
L'Odyssee
Les miserables
Crime et Chatiment
d
��
Crime et Chatiment
Les miserables
L'Odyssee
L'ecume des jours
Le meilleur des mondes
Le petit prince
Germinal
Balou
  • 21
  • 7
  • 3
    `printf("%s\n", titles[tot_books]);` arrays are numbered from zero, valid indexes are `0 .. (tot_books-1)`. The first iteration of the printing loop reaches one beyond the array. –  Sep 29 '21 at 15:14
  • 1
    So you need to decrement `tot_book` before the loop that prints. – Barmar Sep 29 '21 at 15:16
  • 1
    Replace `scanf("%[^\n]\n", titles[i]);` with `scanf("%[^\n]%*c", titles[i]);` to improve the experience at the end of input, but make sure you check the return value. (`fgets` would be even better, though) – William Pursell Sep 29 '21 at 15:16

1 Answers1

1

Arrays are indexed from zero to length - 1

do you need to:

    while (tot_books > 0)
    {
        printf("%s\n", titles[tot_books - 1]);
        tot_books--;
    }

The first problem is explained in the duplicate link.

0___________
  • 60,014
  • 4
  • 34
  • 74