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
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ c language โ€บ strings-in-c
Strings in C - GeeksforGeeks
November 14, 2025 - Instead, strings are implemented as arrays of char. ... #include <stdio.h> int main() { // declaring and initializing a string char str[] = "Geeks"; // printing the string printf("The string is: %s\n", str); return 0; }
๐ŸŒ
Unstop
unstop.com โ€บ home โ€บ blog โ€บ strings in c | initialization and string functions (+examples)
Strings In C | Initialization and String Functions (+Examples)
May 30, 2025 - The source string is initialized as "Welcome to stringsunstop." Then, the first ten characters are changed using the memset() function, and the result, i.e., "$$$$$$$$$$ stringsunstop," is printed on the output screen.
People also ask

What is the difference between declaration and initialization of strings in C?
Declaration reserves memory for a string, while initialization assigns a value. You can declare with char str[10]; and initialize with strcpy(str, "Hello"); or use direct initialization like char str[] = "Hello";.
๐ŸŒ
upgrad.com
upgrad.com โ€บ home โ€บ tutorials โ€บ software & tech โ€บ c string declaration
C String Declaration: Syntax, Initialization & Examples
How to initialize a string in C?
You can initialize a string in C at declaration using double quotes, like char city[] = "Delhi";. This automatically adds the null character at the end of the array.
๐ŸŒ
upgrad.com
upgrad.com โ€บ home โ€บ tutorials โ€บ software & tech โ€บ c string declaration
C String Declaration: Syntax, Initialization & 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
C String Declaration: Syntax, Initialization & Examples
๐ŸŒ
Log2Base2
log2base2.com โ€บ C โ€บ string โ€บ declaration-and-initialization-of-string-in-c.html
Declaration and initialization of string in c
If we assign character by character , we must specify the null character '\0' at the end of the string.
๐ŸŒ
Upgrad
upgrad.com โ€บ home โ€บ tutorials โ€บ software & tech โ€บ c string declaration
C String Declaration: Syntax, Initialization & Examples
June 26, 2025 - 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. You can initialize a string in C at declaration using double quotes, like char ...
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 */
๐ŸŒ
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
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 โˆ’ ยท Using single character constant โˆ’ ยท char string[20] = { โ€˜Hโ€™, โ€˜iโ€™, โ€˜lโ€™, โ€˜lโ€™, โ€˜sโ€™ ,โ€˜\0โ€™} Using string ...
๐ŸŒ
WsCube Tech
wscubetech.com โ€บ resources โ€บ c-programming โ€บ strings
Strings in C Programming (Define, Declare, Initialize, Examples)
August 29, 2025 - Learn how to define, declare, and initialize strings in C programming with clear examples. Understand the basics of working with strings in C. Read now!
Find elsewhere
๐ŸŒ
Scaler
scaler.com โ€บ home โ€บ topics โ€บ c strings - declaring strings in c
C Strings | Declaring Strings in C - Scaler Topics
December 21, 2023 - Highlights: There are four methods of initializing a string in C: Assigning a string literal with size. Assigning a string literal without size. Assigning character by character with size.
๐ŸŒ
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 - char first_name[15] = "ANTHONY"; ... 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....
๐ŸŒ
Codedamn
codedamn.com โ€บ news โ€บ c programming
Strings in C โ€“ String Initialization, Accessing & Displaying
March 10, 2024 - A string in C is essentially a ... as it denotes where the string stops in memory. Strings can be initialized directly by assigning a string literal to a char array....
๐ŸŒ
W3Schools
w3schools.com โ€บ c โ€บ c_strings.php
C Strings
For example, "Hello World" is a string of characters. Unlike many other programming languages, C does not have a String type to easily create string variables. Instead, you must use the char type and create an array of characters to make a string in C:
๐ŸŒ
Codecademy
codecademy.com โ€บ docs โ€บ strings
C | Strings | Codecademy
April 21, 2025 - Master Python while learning data structures, algorithms, and more! ... Strings in C are declared using the char data type, followed by the string name and square brackets []. String values can be initialized in two ...
๐ŸŒ
Programiz
programiz.com โ€บ c-programming โ€บ c-strings
Strings in C (With Examples)
... In C programming, a string is a sequence of characters terminated with a null character \0. For example: ... When the compiler encounters a sequence of characters enclosed in the double quotation marks, it appends a null character \0 at the end by default.
๐ŸŒ
StudyRaid
app.studyraid.com โ€บ en โ€บ read โ€บ 11230 โ€บ 349747 โ€บ string-declaration-and-initialization
String declaration and initialization - C Programming Fundamentals: From Basics to File Handling | StudyRaid
In C, strings are character arrays terminated by a null character \0. Here are the main ways to declare and initialize strings: ... char str1[] = "Hello"; // Array size automatically set char str2[6] = "Hello"; // Explicit size declaration char ...
๐ŸŒ
Filo
askfilo.com โ€บ cbse โ€บ smart solutions โ€บ how do you initialize and declare a string in c programming
How do you initialize and declare a string in c programming... | Filo
December 12, 2024 - Declare a string using a character array: char str[50]; Initialize a string at the time of declaration: char str[50] = "Hello, World!";
๐ŸŒ
Quora
quora.com โ€บ How-do-you-declare-a-string-variable-in-C
How to declare a string variable in C - Quora
Answer (1 of 3): Strictly speaking there is no native string type in C. C developers decided to manage strings as an array of chars ended with a 0. Now, here is the thing, there is a big difference between a string variable and a constant string. That difference is called reserved space. I wil...
๐ŸŒ
Medium
medium.com โ€บ @muirujackson โ€บ char-pointer-to-string-in-c-aa4b59fdf289
Declaration of String in C. In C, char [] and char * are both usedโ€ฆ | by Muiru Jackson | Medium
April 6, 2023 - Attempting to modify a string literal pointed to by a char * results in undefined behavior. Initialization: A char [] can be initialized using a string literal, like "hello", or by assigning each character individually.
๐ŸŒ
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).
๐ŸŒ
Medium
medium.com โ€บ @vcanhelpsu โ€บ string-declaration-and-initialization-35a2718efcf5
String Declaration and initialization | by Vcanhelpsu | Medium
October 7, 2024 - C compiler displays and process ... pointers) in C programs. You can declare and initialize strings using pointers to character strings in C program....