Character Array and String in C

String: String is a collection of character ended with \0.

For example :

main()
{
  char ch[] = { 'a', 'b', 'c', 'd', 'e'}; //character array initialization
  char s[] = "abcd";   //string array initialization
  printf(" %d %d \n",sizeof(ch), sizeof(s));
}

Answer : 5
          5  //5 because string will end with \0 so 1byte it will take

 

How to scan a string and how to print a string?

main()
{
   char s[10];
   printf("Enter a string : \n ");
   scanf("%s",s);
   //note that %s is a format specifier of string
   printf("string data = %s\n",s) //it will print data until \0 will come
}


Answer : Enter a string : codestall
          string data = codestall

Some Useful Notes:

  1. \0 indicates end of string.
  2. \0 is a separator between valid and invalid characters.
  3. for \0 1 byte will be allocated.
  4. \0 means in that 1 byte all bits are zero.
  5. \0 is not a printable character.

Example :

main()
{
char s[10];
printf("Enter a string : \n ");
scanf("%s",s);
//note that %s is a format specifier of string
printf("string data = %s\n",s) //it will print data until \0 will come
}


Answer : Enter a string : code stall
           string data = code

Here, compiler above will not scan data after space.

Solution :

  • If we want to scan data after space use [^\n] format specifier.
  • It will scan until \n will not come.
  • Or you can use direct inbuilt function gets(variable_name).

 

So, I hope you’re all enjoying my blog posts. If yes, then please share this website and do give reviews so that we can improve our methods.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s

Powered by WordPress.com.

Up ↑

%d bloggers like this: