1. Computing

C Tutorial - Lesson Three - About Chars

By

1 of 3

All about Chars
So far the only variables I've covered have been numeric; ints and floats. If we had to limit ourselves to those, it would make programming very limited and processing text next to impossible.

C is perhaps not the easiest language to use for text handling- Both C++ and C# are much better. The problem is that C lacks an explicit string type and uses an array of char.

What is an Array?

An array is a variable that holds a list of variables of the same type and size. A map might hold a two dimensional array (known as a matrix) of ints. An array of char can hold text but the very last character must be a NULL or '\0'.

In an array, the elements are accessed by their position and the first position is always 0, not 1 as in some other languages.

The declaration of an array uses square brackets after the variable name.

 #include <stdio.h>
 #include <string.h>
 
 int main() {
 
 char name[6];
 int values[10];
 strcpy(name,"David") ;
 values[0]= 8;
 printf("My name is %s",name) ;
 return 0;
 }
 

If you Make and run this, you'll see it outputs "My name is David". The %s matches to the first string parameter in the printf() function call, that is the value in name.

I also declared an array of 10 ints and set the first one to a value of 8.

The assignment of the string was done using a function strcpy(). We'll come back to functions in a later lesson. Accept it for now.

On the next page : More on assigning strings.

  1. About.com
  2. Computing
  3. C / C++ / C#
  4. C Programming
  5. C Tutorials
  6. C Tutorial - Lesson Three - About Chars

©2014 About.com. All rights reserved.