8. Character Arrays
There are two ways to use Character Arrays...
char *Array[] = "This is a character array!";
char *Array[80];
The first character array is assigned the string when created. This is
simple but can be simplified using #define...
#define Array "This is a character array!"
The second is a character array with no value, but it allows up to 79
character to be inserted into it. Yes, you heard me right 79, I know it says 80 but, you have to leave one element for a carriage return '\0'. To make this easier how about an example...
---------------chararrays.c------------------
#include <stdio.h>
#define PROMPT "> "
char *info[] = "Enter your name: ";
char *Name[80];
int main()
{
printf("%s\n%s", info, PROMPT);
scanf("%s", &Name);
printf("Your name is %s.", Name);
return(0);
}
-------------------------------------------
Now that wasn't so hard now was it? And guess what that's it for Character Arrays. BUT that isn't it for strings. Here I will give you a little info on some functions built into the 'string.h' file to help you manipulate your character arrays.
STRING.H -
The next example show some of the commands within string.h.
stringhexamle.h
---------------------------------
#inlcude <stdio.h>
#include <string.h>
char * FirstName[32]; /* creates a string for the first name */
char * LastName[32]; /* creates a string for the last name */
char * CopyOfString[64]; /* creates a string to copy to */
char * FullName[]=""; /* creates a string for the full name */
int StringCompared; /* creates an int variable to hold test results. */
unsigned int FullNamesLength; /* creates an int to hold the length of FullName. */
int main()
{
printf("Enter your first name: ");
scanf("%s", &FirstName);
/* Gets the first name from the user */
("Enter your last name: ");
scanf("%s", &LastName);
/* Gets the last name from the user */
strcat(FullName, FirstName);
/* adds the FirstName into FullName */
strcat(FullName, LastName);
/* adds the LastName into FullName */
scanf("Your fullname: %s\n", FullName);
/* Outputs the First and Last Names
to the screen with a space in between */
strncpy(CopyOfString, FullName, 63)
/* Makes a copy of FullName, note the 63
this allows space for the \0 character
that lets the computer know where the
end is. Don't worry too much about this
just always put the number 1 smaller than
the CopyOfString's size */
StringCompared = strcmp(FirstName, LastName);
/* Compares FirstName to LastName
and returns an int letting the
the user know if the names are
bigger smaller or equal to each
other. */
FullNamesLength = strlen(FullName);
printf("FullName is %d characters long.", FullNamesLength);
/* This if statement is pretty self explanitory
I'll let you figure it out. */
if (StringCompared == 0)
{
printf("Your first and last name are the same.\n");
}
else if (StringCompared > 0)
{
printf("Your first name is bigger.");
}
else
{
printf("Your last name is bigger.\n");
}
return 0;
}
----------------------------------
|