Initializing String : Charater Array in C Programming
In the previous chapter we have learnt about declaring array of character i.e String. In this chapter we are looking one step forward - Initializing the String and Different ways of Initializing String.
Initializing String [Character Array] :
Whenever we declare a String then it will contain garbage values inside it. We have to initialize String or Character array before using it. Process of Assigning some legal default data to String is Called Initialization of String. There are different ways of initializing String in C Programming -
- Initializing Unsized Array of Character
- Initializing String Directly
- Initializing String Using Character Pointer
Way 1 : Unsized Array and Character
- Unsized Array : Array Length is not specified while initializing character array using this approach
- Array length is Automatically calculated by Compiler
- Individual Characters are written inside Single Quotes , Separated by comma to form a list of characters. Complete list is wrapped inside Pair of Curly braces
- Please Note : NULL Character should be written in the list because it is ending or terminating character in the String/Character Array
char name [] = {'P','R','I','T','E','S','H','\0'};
Way 2 : Directly initialize String Variable
- In this method we are directly assigning String to variable by writing text in double quotes.
- In this type of initialization , we don’t need to put NULL or Ending / Terminating character at the end of string. It is appended automatically by the compiler.
char name [ ] = "PRITESH";
Way 3 : Character Pointer Variable
- Declare Character variable of pointer type so that it can hold the base address of “String”
- Base address means address of first array element i.e (address of name[0] )
- NULL Character is appended Automatically
char *name = "PRITESH";