0

I wrote a function that copies an array in reverse order

Here:

void reverse(char to[], char from[], int size)
{
    int i;

    i = 0;
    // Copy all the characters before the null character into 'to'. i ends at size-1 for the null character
    while ((to[i] = from[(size-1)-i]))
        ++i;
}

Looking at it again after sometime I noticed that at some point from[-1] in the condition is evaluated. But for some reason my code still works?

I know that there should be junk values here but I want to know why my code "just works" no matter the input. When looking at it through a debugger I still only get '\0' when from[-1] is evaluated. In the end my reverse string is always null terminated lol

I know I can just add to[i] = '\0' to the end to be certain that it's always null terminated but having it this way hasn't caused any issues

This is the code I use it in

#include <stdio.h>

#define MAXLINE 1000

int megetline(char s[],int lim);
void reverse(char to[], char from[], int size);

/* This program reverses it's input a line at a time */
int main()
{
    int len;
    char line[MAXLINE], r_str[MAXLINE];

    while ((len = megetline(line, MAXLINE)) > 0) {
        reverse(r_str, line, len);
        printf("%s", r_str);
    }

    return 0;
}
/* Best time: 0.000070 secs */

int megetline(char s[],int lim)
{
    int c, i;

    for (i = 0; i < lim-1 && (c = getchar()) != EOF && c != '\n'; ++i)
        s[i] = c;
    if (c == '\n') {
        s[i] = c;
        ++i;
    }
    s[i] = '\0';

    return i;
}

void reverse(char to[], char from[], int size)
{
    int i;

    i = 0;
    // Copy all the characters before the null character into 'to'. i ends at size-1 for the null character
    while ((to[i] = from[(size-1)-i]))
        ++i;
}

Your thoughts are greatly appreciated.

starball
  • 20,030
  • 7
  • 43
  • 238
  • 1
    Undefined behaviour. – Retired Ninja Jan 06 '23 at 06:40
  • @RetiredNinja Yes, there answers it. My brain just could apply to this situation for some reason. From playing around with the debugger I noticed that most indices in the array are '\0' but there are sprinkles of junk values. So now I see my program working was just luck. Idk if I should delete or keep this one around for people that had the same confusion as me? – teencorn Jan 06 '23 at 06:58

0 Answers0