String literals
A string is always comes in double quotes “ This is a string in double quotes“
Storing of string literals:
It is always a char* array working behind the string for example printf(“%s”, “Earth”);
%s is the format specifier to string or you can say place-holder in this case we are passing
the base address or starting address of the string.
In actual we are passing “E” and printf itself traverse the whole string to print it and the same
thing happens with scanf.
Perform action in string literals:
char* ptr = “Hello World”;
In this case ptr store the address of first char that is “H”.
For example
Pointer to “H”[0]= 1000
Pointer to “H”[1] = 1000 + 1 (Cause char takes only 1 byte)
NOTE : String literals cant be modified It causes undefined behaviour. String literals
behaves as string constants they have been allocated in a read only memory so we cant
alter them. But yes we can change the whole string.
String literal vs character constant:
A string and char are no to equal in nature. A string points to the first character
of the string but a character constant represent an ASCII value.
Printf function always except a string “This is a string”in its parameter not a character ‘H’.It
always except pointer to character not an integer value.
Declaring a string variable:
A string variable is an one directional array that is capable to hold string at a time.
For example : char s[6]
‘S’ will store 6 character and we always make an array one character longer if length of the
string is 5 than we have to take size of array is 6 so don’t forget to make extra room for
NULL character.
Some c libraries assume that the strings are terminated by NULL so if we don't give the
space to the null character our code gonna give unpredictable result.
Initialising the Array of character:
Method 1 : char s[6] = “Hello”;
Method 2 : char s[6] = {‘H’ , ‘e’ , ‘l’ , ‘l’ , ‘o’};
They both methods are equal but Method 1 is much better than Method 2.
We can modify the character array at any time
But if we initialise the string as pointer to string ie char* ptr = “Hello”
in this case we cant change any character but yes we can change the whole string.
We can initialise Array of character with another method is written below:
char s [ ] = “Hello”
in this case compiler automatically set the length of the array is 6, one extra room for NULL
character.
It looks like you're new here. If you want to get involved, click one of these buttons!