Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does inclusion of {} matter in C string initialization?

Tags:

c

What is the difference between the following?

char input[] = {"abc"};

and

char input[] = "abc";
like image 750
Rn2dy Avatar asked Feb 28 '12 23:02

Rn2dy


People also ask

How to properly initialize a string in C?

A more convenient way to initialize a C string is to initialize it through character array: char char_array[] = "Look Here"; This is same as initializing it as follows: char char_array[] = { 'L', 'o', 'o', 'k', ' ', 'H', 'e', 'r', 'e', '\0' };

Are string arrays mutable in C?

In general, C strings are mutable.

Is possible to modify a string literal?

The behavior is undefined if a program attempts to modify any portion of a string literal. Modifying a string literal frequently results in an access violation because string literals are typically stored in read-only memory.


1 Answers

Both forms are equivalent and permitted.

char input[] = "abc";

or

char input[] = {"abc"};

Here is the relevant paragraph from the C Standard:

(C99, 6.7.8p14): "An array of character type may be initialized by a character string literal, optionally enclosed in braces"

like image 127
ouah Avatar answered Sep 18 '22 17:09

ouah