Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A null character '\0' at the end of a string

I have the following code.

#include <stdio.h>
#include <string.h>

#define MAXLINE 1000

int main()
{
    int i;
    char s[MAXLINE];

    for (i = 0; i < 20; ++i) {
        s[i] = i + 'A';
        printf("%c", s[i]);
    }

    printf("\nstrlen = %d\n", strlen(s)); // strlen(s): 20
    return 0;
}

Should I write

s[i] = '\0';

explicitly after the loop executing to mark the end of the string or it is done automatically? Without s[i] = '\0'; function strlen(s) returns correct value 20.

like image 544
ljosja_ Avatar asked Dec 17 '22 14:12

ljosja_


1 Answers

Yes, you need to add a null terminator yourself. One is not added automatically.

You can verify this by explicitly initializing s to something that doesn't contain a NUL at byte 20.

char s[MAXLINE] = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";

If you do that strlen(s) won't return 20.

like image 150
John Kugelman Avatar answered Dec 31 '22 01:12

John Kugelman