■ FIGURE 5. Pelles C Hello World!.
write your first Hello World program for you as shown in
Figure 5. Next click the ‘Compile’ button, the ‘Execute’
button, and you’ll see the console output shown in
Figure 6.
Whoa! That’s so easy that it almost makes us forget
that there are some not so easy things going on under the
hood, and our job is to learn about those not so easy
things. So, for the time being we will forget about the easy
way to say hello and revert to some more basic C
functions that are closer to the discussion about memory
and pointers.
‘Hello, World!’ The Hard Way
Using an Array
In C, when we want to create a sequence of
characters in memory like we saw in Figure 1, we have
several options. However, the one most closely related to
the memory discussion is to define an array (a continuous
sequence of memory locations) and initialize it with the
data we want stored sequentially in memory. Pelles C
allows us to revert to the original C data types: char for
eight-bit and int for 16-bit (let’s not quibble at this point
about signed and unsigned okay?). So, we create our data
sequence by using:
■ FIGURE 6. Console Hello World!.
70
June 2010
char greet[] = “Hello, World!\n\0”;
This tells the compiler to store the indicated
characters as a sequence in memory. The ‘\n’ and ‘\0’ are
special non-printable characters; the first is newline (an
instruction to the output device to create a new line) and
the second is nul, with a value of 0. We added the ‘\n’
(which isn’t in Figure 1) to separate the output line in the
console display. The following program will output the
data to our terminal:
#include <stdio.h>
int main(int argc, char *argv[])
{
int i;
char greet[] = “Hello, World!\n\0”;
for(i =0 ; greet[i] != ‘\0’; i++)
{
putchar(greet[i]);
}
return 0;
}
This program uses the putchar() function from the
stdio library and reads each character from the memory
one at a time, and outputs each character individually. In
the first program, we used the printf() function, but under
the hood the printf() function calls some code not unlike
what we see here. The ‘for’ loop sends a character from
the greet[] array, increments the address of the array, then
if the value isn’t equal (!=) to ‘\0’ it sends the character. It
loops through each address until it finds the ‘\0’ character,
then it stops.
Using a Pointer
Now suppose we have a bunch of arrays of data and
we want to simplify our lives by writing a function whose
job it is to send out a nul-terminated array (a string) to the
console. We could write a function, consoleOut() and use
it as follows:
#include <stdio.h>
void consoleOut(char *); //declare the function
int main(int argc, char *argv[])
{
char greet[] = “Hello, World!\n\0”;
char south[] = “Howdy, ya’ll!\n\0”;
char north[] = “Get oudda my face!\n\0”;
consoleOut(greet);
consoleOut(south);
consoleOut(north);
return 0;
}
void consoleOut(char *x)
{
int i;