Space for Null character in c strings

Kartik Anand

When is it necessary to explicitly provide space for a NULL character in C strings.
For eg;
This works without any error although I haven't declared str to be 7 characters long,i.e for the characters of string plus NULL character.

#include<stdio.h>

int main(){
    char str[6] = "string";
    printf("%s", str);
    return 0;
}

Though in this question https://stackoverflow.com/a/7652089 the user says
"This is useful if you need to modify the string later on, but know that it will not exceed 40 characters (or 39 characters followed by a null terminator, depending on context)."

What does it mean by "depending on context" ?

Mihai Maruseac

When is it necessary to explicitly provide space for a NULL character in C strings?

Always. Not having that \0 character there will make functions like strcpy, strlen and printing via %s behave wrong. It might work for some examples (like your own) but I won't bet anything on that.

On the other hand, if your string is binary and you know the length of the packet you don't need that extra space. But then you cannot use str* functions. And this is not the case of your question, anyway.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Null character and strings in C

Printing strings and concept of null character in C

Are C constant character strings always null terminated?

How to change newline character with one space when concatenating strings in C?

Joining strings and replacing space with character

regex: change "white space" chracter and - character to null

Array in C and null character

reallocating space on matrix of strings in C

C-style Character Strings

C- Character strings and loops

Strings in R - insert space between selected alphabet character and numeric characters

Doesn't razor accept space as the first character when concat strings?

Replacing Space by Empty Character in c#

Function in C to add <SPACE> after every non space character in a string

Declaring a character array VS dynamically allocating space to character array in C

Check for null character C++

Using the null terminating character as null pointer in C

Replace a # character with a space and a # character

C# joining strings after a specific character

Add a Character Between Strings in C++

how to access a character in an array of strings in c

Trouble Printing Larger Character Strings C++

Why does adding a space between two strings concat the strings in c?

Strings, Decimals and Null in C#

Filter out null character strings from string array

How can I split a string to letters with IFS and read at no space/null, space and at a character -?

warning: null character ignored [-Wnull-character] in C++

Strange behaviour when checking for NULL character in 'C'

How to replace a character in a string with NULL in ANSI C?