Consider below two statements in C. What is the difference between the two?
char s = "geeksquiz"; char *s = "geeksquiz";
Below are the key differences:
The statements ‘char s = “geeksquiz”‘ creates a character array which is like any other array and we can do all array operations. The only special thing about this array is, although we have initialized it with 9 elements, its size is 10 (Compiler automatically adds ‘\0’)
The statement ‘char *s = “geeksquiz”‘ creates a string literal. The string literal is stored in the read-only part of memory by most of the compilers. The C and C++ standards say that string literals have static storage duration, any attempt at modifying them gives undefined behaviour.
s is just a pointer and like any other pointer stores address of string literal.
Running above program may generate a warning also “warning: deprecated conversion from string constant to ‘char*’”. This warning occurs because s is not a const pointer, but stores address of the read-only location. The warning can be avoided by the pointer to const.
This article is contributed by Abhay Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Difference between const char *p, char * const p and const char * const p
- What is the difference between "char a" and "char a"?
- size of char datatype and char array in C
- char* vs std:string vs char in C++
- What is the difference between single quoted and double quoted declaration of char array?
- Difference between char and nchar : MS SQL Server Datatypes
- Wide char and library functions in C++
- C/C++ program to find the size of int, float, double and char
- Convert string to char array in C++
- Difference between Stop and Wait protocol and Sliding Window protocol
- Similarities and Difference between Java and C++
- Difference between Yaacomo and and XAP
- Difference between VoIP and and POTS
- Difference and Similarities between PHP and C
- Difference between Time Tracking and Time and Attendance Software
- Difference Between Single and Double Quotes in Shell Script and Linux
- Difference Between malloc() and calloc() with Examples
- Difference between "int main()" and "int main(void)" in C/C++?
- Difference between ++*p, *p++ and *++p
- Difference Between DOS and Windows