C Strings Initialization

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

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 –

  1. Initializing Unsized Array of Character
  2. Initializing  String Directly
  3. Initializing  String Using Character Pointer

Way 1 : Unsized Array and Character

  1. Unsized Array : Array Length is not specified while initializing character array using this approach
  2. Array length is Automatically calculated by Compiler
  3. 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
  4. 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',''};

Way 2 : Directly initialize String Variable

  1. In this method we are directly assigning String to variable by writing text in double quotes.
  2. 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

  1. Declare Character variable of pointer type so that it can hold the base address of “String”
  2. Base address means address of first array element i.e (address of name[0] )
  3. NULL Character is appended Automatically
char *name = "PRITESH";

Initializing String / Charater Array in C Programming