String in C

A string in the C language is simply an array of characters. Strings must have a NULL or \0 character after the last character to show where the string ends. A string can be declared as a character array or with a string pointer. First we take a look at a character array example:

     char mystr[20];

As you can see the character array is declared in the same way as a normal array. This array can hold only 19 characters, because we must leave room for the NULL character.
Take a look at this example:

 #include<stdio.h>

 int main()
 {
  char mystring[20];

  mystring[0] = 'H';
  mystring[1] = 'E';
  mystring[2] = 'L';
  mystring[3] = 'L';
  mystring[4] = 'O';
  mystring[5] = '\n';
  mystring[6] = '\0';

  printf("%s", mystring);

  return 0;
 }

Note: %s is used to print a string. (The 0 without the ” will in most cases also work).
String pointers are declared as a pointer to a char. When there is a value assigned to the string pointer the NULL is put at the end automatically. Take a look at this example:

 #include<stdio.h>

 int main()
 {
  char *ptr_mystring;

  ptr_mystring = "HELLO";
  printf("%s\n", ptr_mystring);

  return 0;
 }

It is not possible to read, with scanf, a string with a string pointer. You have to use a character array and a pointer. See this example:

 #include<stdio.h>

 int main()
 {
         char my_array[10];
         char *ptr_section2;

         printf("Type hello and enter\n");
                scanf("%s", my_array);
         ptr_section2 = my_array;
         printf("%s\n", ptr_section2);

         return 0;
 }


Previous Page                                               Next Page

Spread the word! By sharing this Post!

Pageviews This Week