Consider below two statements in C. What is difference between 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 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 behavior.
s is just a pointer and like any other pointer stores address of string literal.
Running above program may generates 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 read only location. The warning can be avoided by 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
- strcpy in C/C++
- Arrays in C/C++
- What are the data types for which it is not possible to create an array?
- Enumeration (or enum) in C
- How to pass a 2D array as a parameter in C?
- How to dynamically allocate a 2D array in C?
- Difference between pointer and array in C?
- Are array members deeply copied?
- How to Count Variable Numbers of Arguments in C?
- What is the difference between single quoted and double quoted declaration of char array?
- Initialization of a multidimensional arrays in C/C++
- Write one line functions for strcat() and strcmp()
- gets() is risky to use!
- C function to Swap strings
- Storage for Strings in C