Arrays in C Programming Language
Arrays in C Programming Language
[][][][][][]
Each of the bracket pairs is a slot in the array, and
you can store information in slot--the information
stored in the array is called an element of the
array. It is very much as though you have a group
of variables lined up side by side.
1
Let's look at the syntax for declaring an array.
For example:
char astring[100];
will allow you to declare a char array of 100
elements, or slots. Then you can receive input into
2
it from the user, and when the user types in a
string, it will go in the array, the first character of
the string will be at position 0, the second
character at position 1, and so forth. It is relatively
easy to work with strings in this way because it
allows support for any size string you can imagine
all stored in a single variable with each element in
the string stored in an adjacent location--think
about how hard it would be to store nearly
arbitrary sized strings using simple variables that
only store one value. Since we can write loops that
increment integers, it's very easy to scan through a
string:
char astring[10];
int i = 0;
/* Using scanf isn't really the best way to do this;
we'll talk about that
in the next tutorial, on strings */
scanf( "%s", astring );
for ( i = 0; i < 10; ++i )
{
if ( astring[i] == 'a' )
{
3
printf( "You entered an a!\n" );
}
}
Let's look at something new here: the scanf
function call is a tad different from what we've
seen before. First of all, the format string is '%s'
instead of '%d'; this just tells scanf to read in a
string instead of an integer. Second, we don't use
the ampersand! It turns out that when we pass
arrays into functions, the compiler automatically
converts the array into a pointer to the first
element of the array. In short, the array without
any brackets will act like a pointer. So we just pass
the array directly into scanf without using the
ampersand and it works perfectly.
4
Multidimensional arrays are arrays that have more
than one index: instead of being just a single line
of slots, multidimensional arrays can be thought of
as having values that spread across two or more
dimensions. Here's an easy way to visualize a two-
dimensional array:
[][][][][]
[][][][][]
[][][][][]
[][][][][]
[][][][][]
The syntax used to actually declare a two
dimensional array is almost the same as that used
for declaring a one-dimensional array, except that
you include a set of brackets for each dimension,
and include the size of the dimension. For example,
here is an array that is large enough to hold a
standard checkers board, with 8 rows and 8
columns:
int two_dimensional_array[8][8];
5
You can easily use this to store information about
some kind of game or to write something like tic-
tac-toe. To access it, all you need are two
variables, one that goes in the first slot and one
that goes in the second slot. You can make three
dimensional, four dimensional, or even higher
dimensional arrays, though past three dimensions,
it becomes quite hard to visualize.
<arrayname>[<arrayindexnumber>] = <value>
for instance,
<arrayname>[<arrayindexnumber1>]
[<arrayindexnumber2>] = <whatever>;
6
Let me note again that you should never attempt
to write data past the last element of the array,
such as when you have a 10 element array, and
you try to write to the [10] element. The memory
for the array that was allocated for it will only be
ten locations in memory, (the elements 0 through
9) but the next location could be anything. Writing
to random memory could cause unpredictable
effects--for example you might end up writing to
the video buffer and change the video display, or
you might write to memory being used by an open
document and altering its contents. Usually, the
operating system will not allow this kind of reckless
behavior and will crash the program if it tries to
write to unallocated memory.
#include <stdio.h>
int main()
{
7
int x;
int y;
int array[8][8]; /* Declares an array like a
chessboard */
8
}
What is a String?
Note that along with C-style strings, which are
arrays, there are also string literals, such as "this".
In reality, both of these string types are merely just
collections of characters sitting next to each other
in memory. The only difference is that you cannot
modify string literals, whereas you can modify
arrays. Functions that take a C-style string will be
just as happy to accept string literals unless they
modify the string (in which case your program will
crash). Some things that might look like strings are
not strings; in particular, a character enclosed in
single quotes, like this, 'a', is not a string. It's a
single character, which can be assigned to a
specific location in a string, but which cannot be
treated as a string. (Remember how arrays act like
pointers when passed into functions? Characters
don't, so if you pass a single character into a
function, it won't work; the function is expecting a
char*, not a char.)
To recap: strings are arrays of chars. String literals
are words surrounded by double quotation marks.
9
Remember that special sauce mentioned above?
Well, it turns out that C-style strings are always
terminated with a null character, literally a '\0'
character (with the value of 0), so to declare a
string of 49 letters, you need to account for it by
adding an extra character, so you would want to
say:
char string[50];
This would declare a string with a length of 50
characters. Do not forget that arrays begin at zero,
not 1 for the index number. In addition, we've
accounted for the extra with a null character,
literally a '\0' character. It's important to remember
that there will be an extra character on the end on
a string, just like there is always a period at the
end of a sentence. Since this string terminator is
unprintable, it is not counted as a letter, but it still
takes up a space. Technically, in a fifty char array
you could only hold 49 letters and one null
character at the end to terminate the string.
char *my_string;
10
can also be used as a string. If you have read the
tutorial on pointers, you can do something such as:
For example:
free ( arry );
Using Strings
Strings are useful for holding all types of long
input. If you want the user to input his or her name,
you must use a string. Using scanf() to input a
string works, but it will terminate the string after it
reads the first space, and moreover, because scanf
doesn't know how big the array is, it can lead to
"buffer overflows" when the user inputs a string
that is longer than the size of the string (which acts
as an input "buffer").
11
The prototype for the fgets function is:
12
Let's look at an example of using fgets, and then
we'll talk about some pitfalls to watch out for.
For a example:
#include <stdio.h>
int main()
{
/* A nice long string */
char string[256];
13
getchar();
}
Remember that you are actually passing the
address of the array when you pass string because
arrays do not require an address operator (&) to be
used to pass their addresses, so the values in the
array string are modified.
char input[256];
int i;
14
{
if ( input[i] == '\n' )
{
input[i] = '\0';
break;
}
}
15
strcmp will accept two strings. It will return an
integer. This integer will either be:
16
strcpy is short for string copy, which means it
copies the entire contents of src into dest. The
contents of dest after strcpy will be exactly the
same as src such that strcmp ( dest, src ) will
return 0.
17
entered using fgets. Note that since we make this
into its own function, we
could easily choose a better technique for
removing the newline. Aren't
functions great? */
void strip_newline( char *str, int size )
{
int i;
int main()
{
char name[50];
char lastname[50];
char fullname[100]; /* Big enough to hold both
name and lastname */
getchar();
return 0;
}
Safe Programming
The above string functions all rely on the existence
of a null terminator at the end of a string. This isn't
always a safe bet. Moreover, some of them,
noticeably strcat, rely on the fact that the
destination string can hold the entire string being
appended onto the end. Although it might seem
like you'll never make that sort of mistake,
historically, problems based on accidentally writing
off the end of an array in a function like strcat,
have been a major problem.
21
avoid these issues. Similar to the way that fgets
takes the maximum number of characters that fit
into the buffer, there are string functions that take
an additional argument to indicate the length of
the destination buffer. For instance, the strcpy
function has an analogous strncpy function
22