You are here:About>Computing & Technology>C / C++ / C#> C> C Tutorials> C Tutorial - Lesson Three - About Chars
About.comC / C++ / C#

C Tutorial - Lesson Three - About Chars

From David Bolton,
Your Guide to C / C++ / C#.
FREE Newsletter. Sign Up Now!

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. All about Chars
  2. Assigning Strings using Pointers.
  3. Finishing the Lesson

Previous | Next >>

 All Topics | Email Article | Print this Page | |
Advertising Info | News & Events | Work at About | SiteMap | Reprints | HelpOur Story | Be a Guide
User Agreement | Ethics Policy | Patent Info. | Privacy Policy©2008 About, Inc., A part of The New York Times Company. All rights reserved.