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

19,425

Solution 1

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).

Solution 2

In c "string" means a null terminated array of characters. Compare this with a pascal string which means at most 255 charactes preceeded by a byte indicating the length of the string (but requiring no termination).

Each appraoch has it's pros and cons.

Solution 3

Especially string pointers pointed to array of characters without length known is the only way NULL terminator will determine the length of the string.

Awesome discussion about NULL termination at link

Share:
19,425
ShuklaSannidhya
Author by

ShuklaSannidhya

Updated on June 27, 2022

Comments

  • ShuklaSannidhya
    ShuklaSannidhya almost 2 years

    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...