You're supposed to set it before using it. That's the only rule you have to follow to avoid undefined behaviour. Whether you initialise it at creation time or assign to it just before using it is not relevant.

Personally speaking, I prefer to never have variables set to unknown values myself so I'll usually do the first one unless it's set in close proximity (within a few lines).

In fact, with C99, where you don't have to declare locals at the tops of blocks any more, I'll generally defer creating it until it's needed, at which point it can be initialised as well.

Note that variables are given default values under certain circumstances (for example, if they're static storage duration such as being declared at file level, outside any function).

Local variables do not have this guarantee. So, if your second declaration above (char *str;) is inside a function, it may have rubbish in it and attempting to use it will invoke the afore-mentioned, dreaded, undefined behaviour.

The relevant part of the C99 standard 6.7.8/10:

If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. If an object that has static storage duration is not initialized explicitly, then:

  • if it has pointer type, it is initialized to a null pointer;
  • if it has arithmetic type, it is initialized to (positive or unsigned) zero;
  • if it is an aggregate, every member is initialized (recursively) according to these rules;
  • if it is a union, the first named member is initialized (recursively) according to these rules.
Answer from paxdiablo on Stack Overflow
🌐
Upgrad
upgrad.com › home › tutorials › software & tech › c string declaration
Strings in C: How to Declare & Initialize a String Variables in C
July 15, 2025 - For example, char name[20]; allocates space for a string of up to 19 characters plus the null terminator. You can initialize a string in C at declaration using double quotes, like char city[] = "Delhi";. This automatically adds the null character ...
🌐
Log2Base2
log2base2.com › C › string › declaration-and-initialization-of-string-in-c.html
Declaration and initialization of string in c
There are multiple ways we can initialize a string. If we assign string directly with in double quotes, no need to bother about null character.
Discussions

char* vs char[] when initializing a string
String literals are not mutable. str is an array. Its initial value is the sequence of 17 characters that make up your string. The contents of the array may be changed after this. str2 is a pointer. It points to the first character of a string literal. Since a string literal is not mutable, attempting to change any of the characters in it will yield undefined behaviour. It is a bit of flaw in the language that C even allows: char *str2 = "..."; It would be better to write: const char *str2 = "..."; since this more accurately reflects the immutability of the string literal. The compiler would then complain about this code and prevent it from being compiled, since you would be attempting to pass a const char * argument to a function that needs a char *. (The flaw here is that a string literal is "an array of char", when it really ought to be "an array of const char". But the type of a string literal was set down in stone before the language even had the concept of const, and it can't be changed now without breaking backward-compatibility.) More on reddit.com
🌐 r/C_Programming
20
54
August 3, 2022
Initialize a string in C to empty string - Stack Overflow
I want to initialize string in C to empty string. I tried: string[0] = ""; but it wrote "warning: assignment makes integer from pointer without a cast" How should I do it then? More on stackoverflow.com
🌐 stackoverflow.com
Initializing a string array with a string literal
The compiler can do what it wants here, the standard doesn't say. You can get a string literal in the read-only section even if you use the {'a', ..., '\0'} initialization. More on reddit.com
🌐 r/C_Programming
33
6
July 13, 2024
How do I initialize a string?
If you need a string whose contents you can modify, your best bet for now is to declare an array of char elements big enough to accommodate the largest string you need to create. For example, you could write char permalink[] = "http://redd.it/XXXXXX"; That would introduce the array named permalink. Its type would be array-of-22-char. (Do you see why 22 and not 21?) The definition above is shorthand for the following completely equivalent definition: char permalink[] = { 'h', 't', 't', 'p', ':', '/', '/', 'r', 'e', 'd', 'd', '.', 'i', 't', '/', 'X', 'X', 'X', 'X', 'X', 'X' }; You can modify the contents of permalink in your code, e.g., to replace the X's at the end. And you can use the identifier permalink in most of the ways you use string variables. E.g., you can write strlen(permalink) to compute the string length. What you cannot do is put permalink alone on the left side of the assignment operator (=). It's an array name, but it's not a variable in the same way that a variable of type string is. More on reddit.com
🌐 r/cs50
12
1
January 20, 2014
People also ask

What is a string in C?
A string in C is a collection of characters stored in a character array and ended with a special null character ('\0') that indicates where the string finishes.
🌐
wscubetech.com
wscubetech.com › resources › c-programming › strings
Strings in C Programming (Define, Declare, Initialize, Examples)
How to declare a string in C?
To declare a string in C, you define a character array. For example, char name[20]; allocates space for a string of up to 19 characters plus the null terminator.
🌐
upgrad.com
upgrad.com › home › tutorials › software & tech › c string declaration
Strings in C: How to Declare & Initialize a String Variables in C
Can you declare a string without initializing it in C?
Yes, you can declare a string without initializing it. For example: char str[50];. This creates an uninitialized string buffer, which must be filled before use.
🌐
upgrad.com
upgrad.com › home › tutorials › software & tech › c string declaration
Strings in C: How to Declare & Initialize a String Variables in C
Top answer
1 of 11
15

You're supposed to set it before using it. That's the only rule you have to follow to avoid undefined behaviour. Whether you initialise it at creation time or assign to it just before using it is not relevant.

Personally speaking, I prefer to never have variables set to unknown values myself so I'll usually do the first one unless it's set in close proximity (within a few lines).

In fact, with C99, where you don't have to declare locals at the tops of blocks any more, I'll generally defer creating it until it's needed, at which point it can be initialised as well.

Note that variables are given default values under certain circumstances (for example, if they're static storage duration such as being declared at file level, outside any function).

Local variables do not have this guarantee. So, if your second declaration above (char *str;) is inside a function, it may have rubbish in it and attempting to use it will invoke the afore-mentioned, dreaded, undefined behaviour.

The relevant part of the C99 standard 6.7.8/10:

If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. If an object that has static storage duration is not initialized explicitly, then:

  • if it has pointer type, it is initialized to a null pointer;
  • if it has arithmetic type, it is initialized to (positive or unsigned) zero;
  • if it is an aggregate, every member is initialized (recursively) according to these rules;
  • if it is a union, the first named member is initialized (recursively) according to these rules.
2 of 11
6
I'm wonder, what is the proper way of initializing a string?

Well, since the second snippet defines an uninitialized pointer to string, I'd say the first one. :)

In general, if you want to play it safe, it's good to initialize to NULL all pointers; in this way, it's easy to spot problems derived from uninitialized pointers, since dereferencing a NULL pointer will yield a crash (actually, as far as the standard is concerned, it's undefined behavior, but on every machine I've seen it's a crash).

However, you should not confuse a NULL pointer to string with an empty string: a NULL pointer to string means that that pointer points to nothing, while an empty string is a "real", zero-length string (i.e. it contains just a NUL character).

char * str=NULL; /* NULL pointer to string - there's no string, just a pointer */
const char * str2 = ""; /* Pointer to a constant empty string */

char str3[] = "random text to reach 15 characters ;)"; /* String allocated (presumably on the stack) that contains some text */
*str3 = 0; /* str3 is emptied by putting a NUL in first position */
🌐
GeeksforGeeks
geeksforgeeks.org › c language › strings-in-c
Strings in C - GeeksforGeeks
2 weeks ago - char str[] = "Geeks"; This line declares a character array str and initializes it with the string "Geeks". Internally, this creates an array like: { 'G', 'e', 'e', 'k', 's', '\0'} The null character '\0' is automatically added at the end to ...
🌐
Unstop
unstop.com › home › blog › strings in c | initialization and string functions (+examples)
Strings In C | Initialization and String Functions (+Examples)
May 30, 2025 - Since we used 11 characters (including ... We can initialize a string variable in C by assigning it characters individually and specifying the maximum size of the string as an array size....
🌐
Scaler
scaler.com › home › topics › c strings - declaring strings in c
C Strings | Declaring Strings in C - Scaler Topics
December 21, 2023 - However, it is essential to set the end character as '\0'. For example: Like assigning directly without size, we also assign character by character with the Null Character at the end. The compiler will determine the size of the string automatically. Highlights: There are four methods of initializing a string in C:
Find elsewhere
🌐
WsCube Tech
wscubetech.com › resources › c-programming › strings
Strings in C Programming (Define, Declare, Initialize, Examples)
1 month ago - Learn how to define, declare, and initialize strings in C programming with clear examples. Understand the basics of working with strings in this tutorial.
🌐
Crasseux
crasseux.com › books › ctutorial › Initializing-strings.html
Initializing strings - The GNU C Programming Tutorial
There is no size declaration for the array; just enough memory is allocated for the string, because the compiler knows how long the string constant is. The compiler stores the string constant in the character array and adds a null character (\0) to the end. char *string2 = "A string declared as a pointer.\n"; The second of these initializations is a pointer to an array of characters.
🌐
Guru99
guru99.com › home › c programming › strings in c: how to declare & initialize a string variables in c
Strings in C: How to Declare & Initialize a String Variables in C
August 8, 2024 - In string3, the NULL character must be added explicitly, and the characters are enclosed in single quotation marks. ‘C’ also allows us to initialize a string variable without defining the size of the character array.
🌐
Quora
quora.com › What-are-the-different-ways-of-initializing-a-string-in-C
What are the different ways of initializing a string in C? - Quora
Answer (1 of 2): In C string is a collection of characters. In your example char c[] - It specifies only initialization not an assignment of array. This does not work so gives an error. Called size of c is unknown or zero. c ={“hello”} - This gives an error at compile time because it is ...
🌐
EDUCBA
educba.com › home › software development › software development tutorials › c programming tutorial › string in c
String in C | Learn The Different Ways To Initialize Strings in C
March 27, 2023 - This is a guide to String in C. Here we discuss an introduction, syntax, how to initialize strings in C, along with rules and regulations and respective examples.
Address   Unit no. 202, Jay Antariksh Bldg, Makwana Road, Marol, Andheri (East),, 400059, Mumbai
🌐
Microsoft Learn
learn.microsoft.com › en-us › cpp › c-language › initializing-strings
Initializing Strings | Microsoft Learn
August 3, 2021 - initializes code as a four-element array of characters. The fourth element is the null character, which terminates all string literals. An identifier list can only be as long as the number of identifiers to be initialized. If you specify an array size that is shorter than the string, the extra characters are ignored.
🌐
Reddit
reddit.com › r/c_programming › char* vs char[] when initializing a string
r/C_Programming on Reddit: char* vs char[] when initializing a string
August 3, 2022 -

Hello there friends

I am having a problem understanding why this code will work with a string initialized as char[] vs an string initialized as char*. In essence I am trying to reverse a string in place and has written this:

#include <stdio.h>

void revstr(char *str1, int strLen)
{
    // declare variable
    int i, len;
    char temp;

    for (i = 0; i < strLen/2; i++)
    {
        temp = str1[i];
        str1[i] = str1[strLen - i - 1];
        str1[strLen - i - 1] = temp;
    }
}

    int main()
    {

        char str[17] = "This is a string";
        revstr(str,17);
        printf (" After reversing the string: %s", str);

        char* str2 = "Also a string";
        revstr(str2,13);
        printf (" After reversing the string: %s", str2);

    }

When fed the str, the function behaves nicely. When fed the str2, I get a segmentation and I cannot really understand why :/

Anyone care to explain?

Top answer
1 of 2
55
String literals are not mutable. str is an array. Its initial value is the sequence of 17 characters that make up your string. The contents of the array may be changed after this. str2 is a pointer. It points to the first character of a string literal. Since a string literal is not mutable, attempting to change any of the characters in it will yield undefined behaviour. It is a bit of flaw in the language that C even allows: char *str2 = "..."; It would be better to write: const char *str2 = "..."; since this more accurately reflects the immutability of the string literal. The compiler would then complain about this code and prevent it from being compiled, since you would be attempting to pass a const char * argument to a function that needs a char *. (The flaw here is that a string literal is "an array of char", when it really ought to be "an array of const char". But the type of a string literal was set down in stone before the language even had the concept of const, and it can't be changed now without breaking backward-compatibility.)
2 of 2
14
Apart from the const-ness of string literals, another notable difference is that char local[] = "allocated on stack"; should not be returned by a function, as its lifetime is restricted only until the end of that call (dereferencing such a returned pointer causes undefined behavior for the caller). But const char *immutable = "static storage"; has no such restriction and can be safely returned by a function (and subsequently dereferenced by the caller, but not modified).
🌐
University of Chicago
classes.cs.uchicago.edu › archive › 2020 › winter › 15200-1 › lecs › notes › Lec10Strings.html
Strings
char str1[] = "Hello world"; // allocate 12, initialize to "Hello world" char str2[50] = "Hello world"; // allocate 50, initialize to "Hello world" char str3[] = {'H','e','l','l','o',' ','w','o','r','l','d', '\0'}; // allocate 12, initialize to "Hello world" char str4[12] = {'H','e','l','l','o',' ','w','o','r','l','d', '\0'}; // allocate 12, initialize to "Hello world" char str5[20] = "" // allocate 20, but initialize to empty string · Strings are much like arrays, except for two constraints: ... The length is determined by the location of '\0' This changes what the loop looks like to step through the string. Let's find the length of the string (the number of characters before '\0'): unsigned int stringlength(char s[]) { int length = 0; for (length = 0; s[length] != '\0'; length++) ; // all of the work is being done in the for loop syntax!
🌐
CsTutorialpoint
cstutorialpoint.com › home › string in c [declaration, initializing with example] – cstutorialpoint
String In C [Declaration, Initializing With Example]
May 21, 2025 - Like in the above example the size of str[] is 15 because in this we have initialized a string of 15 characters. ... In this type of initialization, the null character is automatically added to the end of the string, we do not need to write the null character separately at the end of the string.
🌐
Codedamn
codedamn.com › news › c › string-initialization-accessing-displaying
Strings in C – String Initialization, Accessing & Displaying
Over the past several years, Codedamn has grown into a platform trusted by hundreds of thousands of aspiring developers and working professionals to build real-world skills through hands-on practice.
🌐
EngineersHub
engineershub.in › define-c-string-how-to-declare-and-initialize-c-strings-with-an-example
Define C string? How to declare and initialize C strings with an example? - EngineersHub
... A string constant is a sequence of characters enclosed in double-quotes. When string constants are used in the C program, it automatically initializes a null at end of the string.
🌐
TutorialsPoint
tutorialspoint.com › what-is-a-string-declare-and-initialize-the-strings-in-c-language
What is a string? Declare and initialize the strings in C language
March 8, 2021 - HR Interview Questions · Computer Glossary · Who is Who · CServer Side ProgrammingProgramming · An array of characters (or) collection of characters is called a string. Refer to the declaration given below − · char stringname [size]; For example - char a[50]; a string of length 50 characters. The initialization is as follows − ·
🌐
Quora
quora.com › How-do-you-initialize-char*-to-an-empty-string-in-C
How to initialize char* to an empty string in C - Quora
Most answers are wrong semantically as they initialize a pointer to (non-const) char to a string literal that is practically a const array. The correct form is below: ... A “char *” is simply a pointer to an area in memory.