GOEDUHUB Online Courses || Last Batch Student's Projects || COVID-19 Projects(AI-ML) || Universities  ||  Placement Preparation  Subscribe our youtube channel
+91-7976731765 Free Online Tutorials ||  MACHINE LEARNING || Python || DBMS || OOPs || DSA || Java || Linux/Unix ||  C Programming
Register For Online Free Certified Workshops 
0 like 0 dislike
in Tutorial & Interview questions by Goeduhub's Expert (8k points)
String literals represent null-terminated, static-duration arrays of char.

1 Answer

0 like 0 dislike
by Goeduhub's Expert (8k points)
Best answer
String literals represent null-terminated, static-duration arrays of char. Because they have static storage duration, a string literal or a pointer to the same underlying array can safely be used in several ways that a pointer to an automatic array cannot. For example, returning a string literal from a function has well-defined behavior:

const char *get_hello() {    

return "Hello, World!";  /* safe */


For historical reasons, the elements of the array corresponding to a string literal are not formally const. Nevertheless, any attempt to modify them has undefined behavior. Typically, a program that attempts to modify the array corresponding to a string literal will crash or otherwise malfunction.

char *foo = "hello";

foo[0] = 'y';  /* Undefined behavior - BAD! */

Where a pointer points to a string literal -- or where it sometimes may do -- it is advisable to declare that pointer's referent const to avoid engaging such undefined behavior accidentally.

const char *foo = "hello";

/* GOOD: can't modify the string pointed to by foo */

On the other hand, a pointer to or into the underlying array of a string literal is not itself inherently special; its value can freely be modified to point to something else:

char *foo = "hello";

foo = "World!"; /* OK - we're just changing what foo points to */

Furthermore, although initializers for char arrays can have the same form as string literals, use of such an initializer does not confer the characteristics of a string literal on the initialized array. The initializer simply designates the length and initial contents of the array. In particular, the elements are modifiable if not explicitly declared const:

char foo[] = "hello";

foo[0] = 'y';  /* OK! */
 Placements:   List of companies | Logical Reasoning Questions | Quantitative Aptitude Questions | General English Questions | Technical-MCQ and Interview Questions
 Important Lists: List of NITsList of IITsList of Exams After Graduation | List of Engineering Entrance Examinations (UG/PG)College ReviewsCollege Fest, Events & WorkshopsKnowledge ShareTrainees/Interns After 15-04-2020
Exams & Cutoffs: JEE Main | JEE Advanced | GATE | IES | ISROList of PSUs || Cutoff-GATECutoff_IIT-JEECS-ScopeECE ScopeEE-Scope
 Download Previous Year Papers For:  GATE | IES | RAJASTHAN TECHNICAL UNIVERSITY (RTU-Kota)RPSC Technical Exams | ISRO
About Us | Contact Us   Social::   |  |