C - Character arrays vs strings

Introduction

A char array is a string.

You can declare a char array initialized or not.

The format for an initialized char array can look like this:

char text[] = "this";

The array size is calculated by the compiler, so you don't need to set a value in the square brackets.

The compiler adds the final character in the string, a null character: \0.

The code above is like

char text[] = { 't', 'h', 'i', 's', '\0' }; 

The following code loops through the char array one character at a time.

The while loop spins until the \0 character at the end of the string is encountered.

A final putchar() function outputs in a newline.

Demo

#include <stdio.h> 

int main() //from ww  w.  java2  s.  c  o m
{ 
      char sentence[] = "this is a test"; 
      int index; 

      index = 0; 
      while(sentence[index] != '\0') 
      { 
          putchar(sentence[index]); 
          index++; 
      } 
      putchar('\n'); 
      return(0); 
}

Result

Related Topic