Graphics Programs Reference
In-Depth Information
the English language, knowledge of low-level programming concepts can
assist the comprehension of higher-level ones. When continuing to the next
section, remember that C code must be compiled into machine instructions
before it can do anything.
0x261
Strings
The value "Hello, world!\n" passed to the printf() function in the previous
program is a string—technically, a character array. In C, an array is simply a
list of n elements of a specific data type. A 20-character array is simply 20
adjacent characters located in memory. Arrays are also referred to as buffers .
The char_array.c program is an example of a character array.
char_array.c
#include <stdio.h>
int main()
{
char str_a[20];
str_a[0] = 'H';
str_a[1] = 'e';
str_a[2] = 'l';
str_a[3] = 'l';
str_a[4] = 'o';
str_a[5] = ',';
str_a[6] = ' ';
str_a[7] = 'w';
str_a[8] = 'o';
str_a[9] = 'r';
str_a[10] = 'l';
str_a[11] = 'd';
str_a[12] = '!';
str_a[13] = '\n';
str_a[14] = 0;
printf(str_a);
}
The GCC compiler can also be given the -o switch to define the output
file to compile to. This switch is used below to compile the program into an
executable binary called char_array .
reader@hacking:~/booksrc $ gcc -o char_array char_array.c
reader@hacking:~/booksrc $ ./char_array
Hello, world!
r eader@hacking:~/booksrc $
In the preceding program, a 20-element character array is defined as
str_a , and each element of the array is written to, one by one. Notice that the
number begins at 0, as opposed to 1. Also notice that the last character is a 0.
(This is also called a null byte .) The character array was defined, so 20 bytes
are allocated for it, but only 12 of these bytes are actually used. The null byte
Search WWH ::




Custom Search