Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do we need to add a '\0' (null) at the end of a character array in C?

Why do we need to add a '\0' (null) at the end of a character array in C? I've read it in K&R 2 (1.9 Character Array). The code in the book to find the longest string is as follows :

#include <stdio.h>
#define MAXLINE 1000
int readline(char line[], int maxline);
void copy(char to[], char from[]);

main() {
    int len;
    int max;
    char line[MAXLINE];
    char longest[MAXLINE];
    max = 0;
    while ((len = readline(line, MAXLINE)) > 0)
        if (len > max) {
            max = len;
            copy(longest, line);
        }
    if (max > 0)
        printf("%s", longest);
    return 0;
}

int readline(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'; //WHY DO WE DO THIS???
    return i;
}

void copy(char to[], char from[]) {
    int i;
    i = 0;
    while ((to[i] = from[i]) != '\0')
        ++i;
}

My Question is why do we set the last element of the character array as '\0'? The program works fine without it... Please help me...

like image 444
ShuklaSannidhya Avatar asked Dec 16 '12 18:12

ShuklaSannidhya


1 Answers

You need to end C strings with '\0' since this is how the library knows where the string ends (and, in your case, this is what the copy() function expects).

The program works fine without it...

Without it, your program has undefined behaviour. If the program happens to do what you expect it to do, you are just lucky (or, rather, unlucky since in the real world the undefined behaviour will choose to manifest itself in the most inconvenient circumstances).

like image 197
NPE Avatar answered Dec 05 '22 13:12

NPE