Ansi C Tutorial

5 - Sockets and forking

===============================================================================
5 - Sockets and forking.
===============================================================================

In this section there will be alot of new things, socket coding is the code
that makes an application able to connect to another computer or accept
connections from other computers, this is how the internet works.
A socket is an imaginary socket in the computer that opens a port
to send or receav something from the internet or a local network.

I will first make the example code and then I will explain it,
so let's go right to the first example of socket coding:

//----------------------------------------------------------
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <netdb.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

int main ( int argc, char **argv )
{
struct sockaddr_in address;
struct hostent *hp;
int port, sock;
char buffer[1024];

if ( argc < 3 ) {
printf ( "Usage: %s <host> <port>\n", argv[0] );
exit ( -1 );
}

if ( ( sock = socket (AF_INET, SOCK_STREAM, 0 ) ) == -1 ) {
fprintf ( stderr, "Error\n" );
exit ( -1 );
}

printf ( "Resolving hostname...\n" );
if ( ( hp = gethostbyname ( argv[1] ) ) == NULL ) {
fprintf ( stderr, "Could not resolve %s.\n", argv[1] );
exit ( -1 );
}

port = atoi ( argv[2] );
printf ( "Connecting to host.\n" );
address.sin_family = AF_INET;
address.sin_port = htons ( port );
address.sin_addr.s_addr = *( u_long * ) hp->h_addr;

if ( connect ( sock, ( struct sockaddr * ) &address, sizeof ( struct sockaddr ) ) == -1) {
printf ( "Connction refused from host\n" );
exit ( -1 );
}

printf ( "Sending string to host.\n" );
sprintf ( buffer, "Something\r\n" );
send ( sock, buffer, strlen ( buffer ), 0 );
printf ( "Closing connection to host.\n" );
close ( sock );
return 0;
}

//----------------------------------------------------------
So now, what does all this mean ?
First we include the needed header files:
#include <stdio.h> | printf() etc.
#include <unistd.h> | exit(), close()
#include <stdlib.h> | atoi()
#include <netdb.h> | gethostbyname()
#include <string.h> | strlen()
#include <sys/types.h> | socket(), send(), connect()
#include <sys/socket.h> | socket(), send(), connect()
#include <netinet/in.h> | htons()
#include <arpa/inet.h> | (various inet functions)

Then we make and open the main function and then we make the 2 following
structs:

struct sockaddr_in address;
struct hostent *hp;

Then we have the "if the argument counter is less then 3" thing..
Then we have this:
if ( ( sock = socket (AF_INET, SOCK_STREAM, 0 ) ) == -1 )

AF_INET is the domain, SOCK_STREAM is the type and 0 is the protocol,
AF_INET or PF_INET means a normal IP as the domain.
SOCK_STREAM means a two-way connectionbased byte stream.
and 0 means no protocol.
For more info on this, look in the manual page for socket (man 2 socket).

From there to "hp = gethostbyname ( argv[1] )" should be undestandeble.
gethostbyname() will resolve a hostname, for more info on this function
look in the manual page.

Next new things:
address.sin_family = AF_INET;
address.sin_port = htons ( port );
address.sin_addr.s_addr = *( u_long * ) hp->h_addr;

These are declarations of family port and address, you may ask yourself
"where does the names "sin_family" etc. come from ?
They are defined in netinet/in.h.

The next new thing is:
if ( connect ( sock, ( struct sockaddr * ) &address, sizeof ( struct sockaddr ) ) == -1)

First the "( sock," comes from:
if ( ( sock = socket (AF_INET, SOCK_STREAM, 0 ) ) == -1 ) {
And is the socket with which we connect to the other computer.
Then we have a cast, ( struct sockaddr * ), then we have the address and then
bit lenth of the address.
This may be confusing, but that's the way connect() wants it to work.

Next new thing is:
send ( sock, buffer, strlen ( buffer ), 0 );

This will send the buffer to the socket.
send works like this:
int send ( int socket, const void *msg, int len, unsigned int flags );

This tells us that, send is an int.
That it wants a sock (which also is an int), a text message (or a pointer to
one), the string lenth of the message to send, and any flags, which here
is 0 because we aint using any flags.

And then we close the sock and return successful.
-------------------------------------------------------------------------------
You seriously need to play around some with this and read the source several
times to understand it better, you may and should also read this
tutorial more then one time to understand everything, and consult it
when you code things.

-------------------------------------------------------------------------------
Now let's make another example of socket coding and learn to fork() at the
same time.
A fork detaches a whole program or a bit of it from the main program so that
it can be in the background, so that you may log out from the shell but the
process is still running, this is how a daemon / server works.

Now let's make an example of a daemon.
//----------------------------------------------------------
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

int main ( void )
{
pid_t pid;
int sock, send_sock, i;
struct sockaddr_in addr, info;

setsid ( );
umask ( 0 );

signal ( SIGCHLD, SIG_IGN );
if ( fork ( ) ) return 0;
sock = socket ( AF_INET, SOCK_STREAM, 0 );
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl ( INADDR_ANY );
addr.sin_port = htons ( 50 );

bind ( sock, ( struct sockaddr *) &addr, sizeof ( addr ) );
i = sizeof ( info );
listen ( sock, 1 );

for (;;) {
i = sizeof ( info );
send_sock = accept ( sock, ( struct sockaddr * ) &info, &i );

pid = fork ( );
if ( pid ) {
close ( send_sock );
continue;
}
else {
send ( send_sock, "sh-2.03# ", 9, 0 );
sleep ( 4 );
send (send_sock, "\nNah, just kidding :P\n", 24, 0);
sleep ( 3 );
close ( send_sock );
return 0;
}
}
return 0;
}

//----------------------------------------------------------
So now what does this mean ?
First we include the header files and create a main function.
Then we declare pid as pid_t, so that we have a pointer to the pid
(process ID), then we make a struct with pointers addr and info.
Then we use setsid(), (man 2 setsid for info on it).
And after that we use umask(), this is used to set the file premission,
you may "man 2 umask", if you wanna know exectly what it does.
The we use signal to ignore the sigchld, man 2 signal for more info on why
it acts the way it acts.
The we say:
if ( fork ( ) ) return 0;
This means that if the process if forked it should return successfully.
Then we create a socket.
And after that declare the ports etc. in the struct.

Then we use bind:
bind ( sock, ( struct sockaddr *) &addr, sizeof ( addr ) );

sock is the socket, and then there is the cast, the address and the
bit size of the address.

Then we say that i is the bit size of info.
i = sizeof ( info );

And then we say for it to listen on the sock we used bind to open.
listen ( sock, 1 );
The 1 in listen is the backlog (look in the manyal page for this).
Then we make a loop that may go on for ever that says:
That i is the bit size of info, again .... I had some problems with the
code when it wasnt there.
i = sizeof ( info );
And then we say that send_sock is like this:

send_sock = accept ( sock, ( struct sockaddr * ) &info, &i );
this means that send_sock is the accept, and so it's the incoming socket
connection.

Then we make sure that the pid is forked and so put to the background,
pid = fork ( );

If there is a pid, then close the socket and continue.
.....
if ( pid ) {
close ( send_sock );
continue;
}
.....

else do this (if it works out the way it's made to do:
.....
send ( send_sock, "sh-2.03# ", 9, 0 );
sleep ( 4 );
send (send_sock, "\nNah, just kidding :P\n", 24, 0);
sleep ( 3 );
close ( send_sock );
.....

This means send "sh-2.03# " to the user at the other end, and then
wait for 4 seconds and after that send "Nah, just kidding :P",
wait for another 3 seconds and then close the socket.

As we did:
addr.sin_port = htons ( 50 );

This daemon will be listening on port 50 ...
And since we are using raw socks, this will have to be started as user root.

Now I know I'm not explaining this as easy as I did with other codes, but
I'm doing that for a reason, to make you think and to get more "aha"
experiances.
So that you learn some by your self, else you're likly to just forget
about it as soon as you read it .... so play around with the code until
you understand it, and dont be afraid of the manual pages.
See how much of the code you can change etc.

-------------------------------------------------------------------------------
Here is a little code with the forking part alone:
//----------------------------------------------------------
#include "check_tmp.h"
/* taken from Stevens APUE */
int become_daemon(void){

pid_t pid;
if ( (pid = fork()) < 0)
return(-1);
else if (pid != 0)
exit(0); /* death to the parental unit */

setsid();
/* we're going to fork again for annoying SYSVr4 to insure that
we have no controlling terminal */

if ( (pid = fork()) < 0)
return(-1);
else if (pid != 0)
exit(0); /* death to the parental unit */
chdir("/");
umask(0);
return(0);
}

//----------------------------------------------------------
This code is taken litterly from another source, and I will not change or
explain it, look at it as a little test, of how well you know C by now ....
Figure out exectly what it's doing and why, use the manual pages.

(No it wont compile as it is, because there is no main function and the header
files are missing.)

-------------------------------------------------------------------------------
Actually there's not much more to say about forking and raw sockets at
this point ... there is ALOT more to sockets, but nothing you need to know
at this point since this is not a socket coding tutorial.

So off to the next section.

4 - Some theoretical C programming with more basics, Makefiles and styles.

===============================================================================
4 - Some theoretical C programming with more basics, Makefiles and styles.
===============================================================================

This section will be quite short, here I'll explain how you should think
when you make ideas for a program and the difference between the Bell Labs
(K&R - Kerninghan and Ritche) style and student style.

So let's start with how to plan and think when you do a program.
-------------------------------------------------------------------------------
If you plan at all when you make a program, and you should if you want it
to work well, you should take a paper and a pen and draw what you want each
function to do, make each function as a little box and start, just free
dream thinking, let me illustrate what I mean with an example:

-------------------------------------------------------------------------------
___________________________
|                           |
|      main function        |
| calls the other functions |
|___________________________|               ______________________
|                             |                      |
|                             |   usage function...  |
|-----------------------------|  if ( argc != 2 ) {} |
|                             |   return -1 if not.  |
|                             |______________________|
|
|                              ______________________
|                             |                      |
|                             | funct1 should import |
|-----------------------------| an argc and return   |
|   that + itself -1   |
|______________________|
|
|
|
|
__________|___________
|                      |
| funct2 should printf |
|    the resault of    |
|        funct1        |
|______________________|

-------------------------------------------------------------------------------
Here we have a number of boxes which each resembles a function, with little
notes in them, now let's make the program that this example illustrates:

//----------------------------------------------------------
#include <stdio.h>
#include <unistd.h>

void usage ( int i, char *myname );
int funct1 ( int i );
void funct2 ( int i );

int main ( int argc, char **argv )
{
usage ( argc, argv[0] );
funct2 ( funct1 ( argc ) );
return 0;
}

void usage ( int i, char *myname )
{
if ( i != 2 ) {
fprintf ( stderr, "Usage: %s <argument>\n", myname );
return -1;
}
}

int funct1 ( int i )
{
int x;
x = ( i + i - 1 );
return ( x );
}

void funct2 ( int i )
{
printf ( "The resault of argc + it self - 1 = %i\n", i );
}

//----------------------------------------------------------
There are 4 new things in this code that I will explain before doing anything
else, the new things are:

#include <unistd.h>
This we include because we use the exit() function.
This means that the exit() function with syntax is described in unistd.h.

And then we have the:
exit ( -1 );
This means kill the program with status unsuccessful, exit doesn't return
anything.

And then:
funct2 ( funct1 ( argc ) );
and
return ( x );

Now, funct1( argc ) will return something from it's "return ( x );", which
in this case is an integer, and so we can use "funct1( argc )" as an integer,
so when we say "funct2 ( funct1 ( argc ) );" we use the output of
"funct1( argc )" as the input to funct2().

If you dont really understand it, read the code again and what I just said,
and if you still dont understand it, dont worry, I'll explain it again
later.

So now, if you read the source and compare it to the idea with the boxes
you'll come to the conclution that the boxes we drew are the same idea
as the program, just written in a human way instead of a computer way.

This way of thinking is also called "modular thinking", that every function
is a part and you can add as many parts as you want as long as the
main program allows them to integrate with it.

When you start to think modular, it will be really easy to make and think
like the functions, and it will make programming very much easyer.

Don't just read this as text and then continue, make sure to put the example
code in a file and compile it so you can try it, and play around with it, like
rewriting some of the code just to see what happens.

-------------------------------------------------------------------------------
Now let's take a look on how to make a Makefile.
Let's use our last program as an example, so let's cut it up in several
files (it's easyer if you make a dedicated directory for this):

program1.h:
//----------------------------------------------------------

#include <stdio.h>
#include <unistd.h>

void usage ( int i, char *myname );
int funct1 ( int i );
void funct2 ( int i );

//----------------------------------------------------------

main.c
//----------------------------------------------------------

#include "program1.h"
int main ( int argc, char **argv )
{
usage ( argc, argv[0] );
funct2 ( funct1 ( argc ) );
return 0;
}

//----------------------------------------------------------

usage.c
//----------------------------------------------------------

#include "program1.h"
void usage ( int i, char *myname )
{
if ( i != 2 ) {
fprintf ( stderr, "Usage: %s <argument>\n", myname );
exit ( -1 );
}
}

//----------------------------------------------------------

funct1.c
//----------------------------------------------------------

#include "program1.h"
int funct1 ( int i )
{
int x;
x = ( i + i - 1 );
return ( x );
}

//----------------------------------------------------------

funct2.c
//----------------------------------------------------------

#include "program1.h"
void funct2 ( int i )
{
printf ( "The resault of argc + it self - 1 = %i\n", i );
}

//----------------------------------------------------------
And then we make the Makefile:
//----------------------------------------------------------
HDRS = program1.h
OBJS = main.o usage.o funct1.o funct2.o
SRCS = main.c usage.c funct1.c funct2.c

CC = gcc -g -Wall -O3
all:    $(OBJS) program1
main.o: $(HDRS) main.c
$(CC) -c main.c

usage.o:        $(HDRS) usage.c
$(CC) -c usage.c

funct1.o:       $(HDRS) funct1.c
$(CC) -c funct1.c

funct2.o:       $(HDRS) funct2.c
$(CC) -c funct2.c

program1:       $(OBJS)
$(CC) main.o usage.o funct1.o funct2.o -o program1

clean:
rm -rf *.o core program1 *~

//----------------------------------------------------------
Now let me explain the Makefile.
First, if there is more then 2 spaces in a row in the Makefile then it's
a TAB and not spaces.
Now first in the Makefile we set the variables.
HDRS, OBJS, SRCS and CC.

HDRS is the header files to be included, and here we made our own, so that
we can inclue it in every file, because the header file is in the same dir
as the source and not in any real include dir we have it enclosed by
quotes "" instead of <>.

Then we set OBJS, which is the object files that should be created from the
source..

Then we set the SRCS, which is the source files, that is all the files
we are going to compile.

And then we set CC, which is the C Compiler with or without flags..
You can set the flags separatly with "CFLAGS = -g -Wall -O3" or whatever
flags you want and use them as "$(CC) $(CFLAGS)", but here we set the
flags "-g -Wall -O3" in the CC, and just so you know, "-g" means
debugging information, I'll explain this later, and "-Wall" means "Warn all"
and it will warn about any error, even if it doesnt matter if it's there.
And then we have "-O3" wich menans "Optimize 3 levels", this will optimize
your bianry (compiled source - program).

Then we have:
"all" is the default action when you type "make" and it will run the program1
'function' later in the Makefile.

all:    $(OBJS) program1
This tells the compiler how to do the main.o (object) file.
main.o: $(HDRS) main.c
$(CC) -c main.c

This tells the compiler how to do the usage.o file.
usage.o:        $(HDRS) usage.c
$(CC) -c usage.c

And the same for funct1 and funct2 ......
And here is the program1 'function'.
This will link the object files to a binary program named "program1",
this Makefile is made so that if it dont find an object file at this point
it will make it from the source.

program1:       $(OBJS)
$(CC) main.o usage.o funct1.o funct2.o -o program1

And finally the clean 'function', so if you type "make clean" it will
remove all object files, any core file etc.

clean:
rm -rf *.o core program1 *~

-------------------------------------------------------------------------------
That was is a recursive Makefile ....
The same Makefile but not recursive would look like this:
//----------------------------------------------------------
CC = gcc -g -Wall -O3
all:    program1
program1:
$(CC) -c main.c
$(CC) -c usage.c
$(CC) -c funct1.c
$(CC) -c funct2.c
$(CC) main.o usage.o funct1.o funct2.o -o program1
clean:
rm -rf *.o core program1 *~

//----------------------------------------------------------
It's about the same thing, but it wont act as 'modular' as the recursive one.
-------------------------------------------------------------------------------
Now let's take a look at styles in C, I've already said that my examples here
are in K&R / Bell Labs style, but there is also student style, let's make a
short example first one in Bell Labs style and then the same in student style.

Bell Labs style:
//----------------------------------------------------------

#include <stdio.h>
int main ( int argc, char **argv )
{
if ( argc != 2 ) {
fprintf ( stderr, "Usage: %s <argument>\n", argv[0]);
return -1;
}

  printf ( "The argument was %s\n", argv[1] );
return 0;
}

//----------------------------------------------------------

Student style:
//----------------------------------------------------------

#include <stdio.h>
int main(int argc,char **argv)
{
if(argc!=2){fprintf(stderr,"Usage: %s <argument>\n",argv[0]);
return -1;}
printf("The argument was %s\n",argv[1]);
return 0;}

//----------------------------------------------------------
Now as you can see, Bell Labs style is much cleaner and much easyer to read.
So what is the actual difference ?
Well, a Bell Labs style function looks like this:

function ( ) {
action;
}

While a Student style function looks like this:
function(){action;}
Bell Labs style has the opening { on the same line as the function
and the closing } on a line by it self, with the action inbetween.
And then Bell Labs style has alot of spaces and *air* in the code
to make it easy to read for your self and others if you're in a
coding team.

All professional programmers I've seen this far uses Bell Labs style.
Let's not go deeper into the difference of the styles, just know that
there are different styles so you dont get confused if you see codes that
look really bizzare and *home made*.

-------------------------------------------------------------------------------
So now on to some more new stuff in C, to make it even easyer, to do some
stuff.

I've said that "strlen ( pointer )" will return the string length of the
pointer as an integer, but there is another one just like that.

sizeof ( pointer );
This will return the bit size of a pointer, so say that a pointer contains
the string "1234", strlen will return 4, since it's 4 bytes long, while
sizeof will return 16 since 4 * 8 == 16 ( there is 8 bits for 1 byte ).

I've also talked about strcmp() and strcpy(), now I wanna say that there
is 2 more, just like those but that's more *secure*, strncmp and strncpy.
The difference is that strncmp and strncpy wants the strlen of the string too.
Let me show you:

strcpy ( ptr, "string" );
strncpy ( ptr, "string", 6 );

strncmp ( ptr, "string" );
strncmp ( ptr, "string", 6 );

Now this is really easy once we know about strlen().
Like this:

strncmp ( ptr, argv[1], strlen ( argv[1] ) );
See ?
Another thing is the write() function, it works almost as fprintf, but
it wants the strlen, let me show you:

write ( 0, argv[1], strlen ( argv[1] ) );
This will have the same effect as doing either:
printf ( "%s", argv[1] );
or rather:
fprintf ( stdout, "%s", argv[1] );

the 0 in write() is a file descriptor, 0 means none or default which is
stdout, but you can write to a file if you've opend it (I'll show you that
soon), or a socket (I'll take up that too) etc.

there is alot of those small functions, like:
strchr()
memmem()
strcat()
memcpy()
memcmp()
calloc()
realloc()
stat()
fstat()
fseek()
atol()
strtod()
strtol()
strtoul()

And so on for a good while .... It's pretty pointless trying to learn
all of them at once .... and this is a tutorial not a library refference.
So I will not go over all functions in the whole language, if you wanna
learn all functions there is, get a book or find some place online
that has them all.
This tutorial will have enough to teach you the actual language well
enough so you can make your own programs at need, and so that you
without problems can learn all the extra stuff if you want.

A trick to find a function you're looking for on a UNIX system is this:
Say that you want to find something that converts ASCII (characters)
to integers but you never heard about atoi(), then you can do this:

alien:~$ apropos integer
That will show you this:
Tcl_GetInt, Tcl_GetDouble, Tcl_GetBoolean (3) - convert from string to integer,
double, or boolean
Tcl_NewIntObj, Tcl_NewLongObj, Tcl_SetIntObj, Tcl_SetLongObj, Tcl_GetIntFromObj, Tcl_GetLongFromObj (3) - manipulate Tcl objects as integers
abs (3)              - computes the absolute value of an integer.
atoi (3)             - convert a string to an integer.
atol (3)             - convert a string to a long integer.
div (3)              - computes the quotient and remainder of integer division
labs (3)             - computes the absolute value of a long integer.
ldiv (3)             - computes the quotient and remainder of long integer division.
rint (3)             - round to closest integer
strtol (3)           - convert a string to a long integer.
strtoul (3)          - convert a string to an unsigned long integer.
tixGetInt (n)        - Get the integer value of a string. ' ' '
Math::BigInt (3)     - Arbitrary size integer math package
integer (3)          - Perl pragma to compute arithmetic in integer instead of double
line 1/14 (END)

And there we go, the 4th down says:
atoi (3)             - convert a string to an integer.

press "q" to get the prompt back:
so now you can do:
alien:~$ man 3 atoi
The 3 after man comes from "atoi (3)", and "man" means manual.
Now you will get up a manual page that has this in it:
---------------------------------------
SYNOPSIS
#include <stdlib.h>

       int atoi(const char *nptr);
---------------------------------------

That is the most important part for you.
First it tells you what header file to include, and then it tells you
the type and syntax of the function.

Here, the function is of type int so it may be used as an integer,
and the syntax of it is: const char *nptr, wich means a char pointer.

(press "q" to get out of the man page and back to the prompt)
So this means the following, illustrated in a small code:
//----------------------------------------------------------
#include <stdio.h>
#include <stdlib.h>

int main ( void )
{
char something[10];
strcpy ( something, "123" );
printf ( "the pointer holds %i\n", atoi ( something ) );
return 0;
}

//----------------------------------------------------------
Not very hard is it ?
look up the man pages for funtions that you already know to learn
how the manual pages works and are written.

-------------------------------------------------------------------------------
Now it's time to move on to the next section:

3 - A little more advanced basics

===============================================================================
3 - A little more advanced basics.
===============================================================================

Here we will look at the basics of dynamic memory allocation, functions,
struct, typedef, define and some other new things.

So let's not waste time on weird elaborations of nothing, here we go with
the simple basics of dynamic memory allocation:

-------------------------------------------------------------------------------
As I've mentiond, to create a char pointer you need to allocate space for it,
like this:

char ptr[10];
That is a char pointer named ptr that can hold 10 bytes, or 80 bits (there's 8
bits in one byte), but the downside of that is that you have to know how much
memory it will use... and sometimes you dont know that.

So here is where the malloc() function comes handy, malloc means
memory allocation or memory allocate.

So first thing we need to create a pointer that has no memory allocated, that
we do like this:

char *ptr;
This would be the same as to say:
char ptr[];
Since a [] at the end means the same as a * in the beginning when you
declare pointers.
But *ptr; looks better.

The next thing you need is to allocate the memory to it dynamicly, that
you do something like this:

ptr = (char *) malloc ( strlen ( str ) );
Now what does that mean ?
First, the pointer equals the rest of the line, and the rest of the line
means, first we have (char *) which is called a cast.
A cast tells the program what sort of memory it should alocate, if it's
a void if it's an int or if it's a char or any other data type.

The next thing is the malloc( strlen(str) );, that means that it will
allocate the same amount of bytes as the str pointer is long.

Now that may seem confusing at this point since the pointer contains
nothing yet, but at the time it compiles the compiler will look at the whole
thing and see how long it will be.

A note is that the strlen() is a new thing here, let's make a simple
example of the strlen() function so you understand it (strlen needs string.h):

//----------------------------------------------------------
#include <stdio.h>
#include <string.h>

int main ( int argc, char **argv )
{
int i;
i = ( strlen ( argv[1] ) );
printf ( "The first argument was %i characters long.\n", i );
return 0;
}

//----------------------------------------------------------
Now, that should be understandeble, and if it isn't, try it.
(A note is that the program will 'segmentaion fault' if you dont
supply any arguments, this means that it will try to read memory that's
not there... to fix that you can add an "if ( argc != ..... etc.").

So, now we should be ready to make a little example program with
dynamic memory allocation, let's call the file program2.c
//----------------------------------------------------------
#include <stdio.h>
#include <string.h>

int main ( int argc, char **argv )
{
int i;
char *ptr;

  if ( argc != 2 ) {
fprintf ( stderr, "Usage: %s <argument>\n", argv[0]);
return -1;
}

  i = ( strlen ( argv[1] ) );
ptr = (char *) malloc ( i + 10 );
strcpy ( ptr, argv[1] );

printf ( "The argument was: %s and that is %i characters long.\n", ptr, i );
return 0;
}
//----------------------------------------------------------
Now let's take a look at what we have done here.
First we include the stdio.h header file.
The we make the main function that can import arguments and keep count of them,
and then open the function with a bracket.
Then we declare i as an int and ptr as a pointer with no memory allocated
at this point.

Then we check if the argument counter is 2 or not.
And if not, then we display the usage, and then we exit the program with
status unsuccessful, else we go on to:

i is the string lenth of argv[1].
The memory for ptr should be treated as char space, and the memory allocation
should be i (the string lenth of argv[1]) + 10 (so if argv[1] has a string
lenth of 10 it will allocate 20, this is a good precaution to make sure we
have enough memory allocated).
And then we copy the contents of argv[1] to ptr.

After that we print out the resault and exit with status success.
-------------------------------------------------------------------------------
This program executed looks like this:
alien:~$ ./program2 foo
The argument was: foo and that is 3 characters long.
alien:~$

alien:~$ ./program2 testing
The argument was: testing and that is 7 characters long.
alien:~$

-------------------------------------------------------------------------------
Now let's have a look at structures in C.
When you make a struct you should think of it as if you create your own
data type as char, int, void etc.
So let's go right to an example with a struct:

//----------------------------------------------------------
#include <stdio.h>
int main ( void )
{
struct mystruct {
char buffer[20];
};
struct mystruct one;

  sprintf ( one.buffer, "something" );
printf ( "%s\n", one.buffer );
return ( 0 );
}

//----------------------------------------------------------
So what does this mean ?
Let's go right to the new part:
.....
struct mystruct {
char buffer[20];
};
struct mystruct one;
.....

first we create a struct where test is the type, and it holds one member,
a char named buffer that can hold 20 bytes.
Note that the end bracket in the structure have to have a semi-colon after it.

And then we say "struct test one;" to create a pointer to the stuct so that
we can call the member(s) from the actual struct.

This means that "one.buffer" is the member buffer from the structure
pointed to by one, and will work as a pointer.

The "." dot, is a structure operator, and it connects the struct name and the
member name, so that it works as a pointer as just said.

This should make it clear.
Now, there is more then one way of doing this, so here is another example:
//----------------------------------------------------------
#include <stdio.h>
int main ( void )
{
typedef struct mystruct my_struct;
struct mystruct {
char buffer[20];
};

  my_struct *one;
  sprintf ( one->buffer, "something" );
printf ( "%s\n", one->buffer );
return ( 0 );
}

//----------------------------------------------------------
So what does this mean ?
Let's go right to the new part again:
.....
typedef struct mystruct my_struct;
struct mystruct {
char buffer[20];
};

  my_struct *one;
.....

typedef sorta renames "struct mystruct" to "my_struct", you need to do this
so you can declare "one" as a pointer to the struct function "my_struct *one;".

This means that you use "one->buffer" instead of "one.buffer" to point
to the member of the struct.

This will come to use later.
-------------------------------------------------------------------------------
Now let's take a short look at define, here is an example:
//----------------------------------------------------------
#include <stdio.h>
#define ONE 1
int main ( void )
{
printf ( "%i\n", ONE );
return 0;
}

//----------------------------------------------------------
As you can see this is really simple, you just define "ONE" as "1",
you can say:

#define USA 01
#define SWE 46
#define AUS 61

Or whatever ..... and so the USA, SWE and AUS can be used as variables in
the code.

-------------------------------------------------------------------------------
Now let's take a look at functions, to this point we have only made one
main function in each program, but let's change that.
Actually the main function in a program should be as short as possible,
and only used to call for the other functions.

So let's make an example of a little program with more then one function.
Let's call the file program3.c

//----------------------------------------------------------
#include <stdio.h>
int usage ( int i, char *myname );
int main ( int argc, char **argv )
{
usage ( argc, argv[0] );
printf ( "The argument was %s\n", argv[1] );
return 0;
}

int usage ( int i, char *myname )
{
if ( i != 2 ) {
fprintf ( stderr, "Usage: %s <argument>\n", myname);
return -1;
}
}

//----------------------------------------------------------
So now what does this mean, and why ?
First we inclide the standard input output header file as usual.
The we do something new, we declare a funciton, this you do as here,
simply by typing the full function name with what it may import
and a semi colon ";" after it.

Then we make a main function that may import the argument counter as
an integer and the actual arguements as characters, where on we open
the main function.

Then we call for the usage() function and export argc and argv[0] to it.
And after it has performed that function it will print out the printf line,
and then exit with success.

Now the usage() function ......
First we create it and import an integer and name it "i" and a char that
we name myname, and then open the funtion.

Then we ask if i (which was imported from argc and has argcs value),
is anything else then 2, and if it is anything else then 2, then
it will display the usage and return with status unsuccessful.

Note that the char myname will hold the value of argv[0].
And then we close that function.
-------------------------------------------------------------------------------
This program executed looks like this:
alien:~$ ./program3 foo
The argument was foo
alien:~$

alien:~$ ./program3
Usage: ./program3 <argument>
alien:~$

-------------------------------------------------------------------------------
So now, what's the real point of functions ?
A function is really designed to import something and return something else.
This is the whole thing about a program with arguments aswell, so
you could say that a function is a program within the program.

Another good point of functions is that when you have really big projects
that are several thousen lines of code, then one file is to easy to
loose over view of, so then you can make one file for each function
and use a Makefile to compile it, I will explain this later.

Almost everything you use are functions, like printf is a function
described with syntax and all in stdio.h, that's why you need header files,
I will breafly explain header files and how to make them later.

Functions are good to use, and even if you're making a small program
you should always make a habit of making separat functions, and call them
from the main function.

-------------------------------------------------------------------------------
Here is another example with several functions, let's name the file functions.c
//----------------------------------------------------------
#include <stdio.h>
int usage ( int i, char *myname );
void diplay1 ( char *argument );
void diplay2 ( void );

int main ( int argc, char **argv )
{
usage ( argc, argv[0] );
diplay1( argv[1] );
diplay2();
return 0;
}

int usage ( int i, char *myname )
{
if ( i != 2 ) {
fprintf ( stderr, "Usage: %s <argument>\n", myname);
return -1;
}
}

void diplay1 ( char *argument )
{
printf ( "Here is what's in diplay1() and argv[1] was: %s\n", argument );
}

void diplay2 ( void )
{
printf ( "Here is what's in diplay2()\n" );
}

//----------------------------------------------------------
First we include the header file like always.
Then we decalare the functions that we will use, (note that display 1 & 2
are void, because they dont return anything to the system).

Then we create a main function and open it.
Then we call for the functions, usage(), and export argc and argv[0] to it.
And then we call for diplay1(), and export argv[1] to that, and after that
we call for diplay2() to which we export nothing.

And then we return success and exit.
The usage function is the same as before.
Then we have the diplay1 function, which imports a char that we have named
argument, which will contain argv[1] because that's what we exported to it.

And what's in diplay1() should be understandeble, same goes for what's in
diplay2().

I will go deeper into what a function can return more then 0 or -1 in a while,
when I take up Makefiles etc.

At this point you should play around some with this and practice.
This brings us to the next section:

2 - Basic C programming

===============================================================================
2 - Basic C programming.
===============================================================================

Now when you know how a pointer works, what an int is, and you can use
sprintf and printf, it's time to move on to the next step.

The things I will take up first here is the if and else statement in C,
the for loop and the scanf function.

And then the argument vectors and argument count (argv and argc), and
also strcpm, strcpy and atoi.

So here we go with the if statement.
-------------------------------------------------------------------------------
The if statement works like this:
if ( condition ) { action } else { other-action }
Let me demonstrate this in a code, make a file called ifstate.c and in it do:
//----------------------------------------------------------
#include <stdio.h>
int main ( void )
{
int i;

i = ( 1 );
if ( i == 1 ) {
printf ( "i is 1\n" );
}
else
{
printf ( "i isnt 1\n" );
}
return 0;
}

//----------------------------------------------------------
Here we have it:
if ( condition ) { action } else { other-action }

The condition is i == 1, so if i is 1 (which it is from "i = ( 1 );"), then
it will perform the action which is to print "i is 1" to the screen,
else it will perform the other-action which is to print "i isnt 1" to
the screen.
If you in this code change the "i = ( 1 );" to "i = ( 2 );", then it
will print the other-action instead of the action.

This will look like this executed:
alien:~$ gcc -o ifstate ifstate.c
alien:~$ ./ifstate
i is 1
alien:~$

-------------------------------------------------------------------------------
So why do we do == in the if and not only = ?
C uses the boolean operators, which is as follows:

-------------------------------------------------------------------------------
== equal to.
!= not equal to.
|= or equal to.
> greather then.
>= greather then or equal to.
< less then.
<= less then or equal to.
&& and.
|| or.

-------------------------------------------------------------------------------
Here is another example with the if statement.
//----------------------------------------------------------
#include <stdio.h>
int main ( void )
{
int i, x;

i = ( 10 + 10 );
x = ( i );

if ( x < 50 ) {
printf ( "x is %i\n", x );
}
else
{
printf ( "x is %i\n", i );
}
return 0;
}

//----------------------------------------------------------
So what does this do ?
First we declare integers, i and x, and then we make i = 10 + 10 which
needless to say is 20, and then we make x = i, so that x is now 20.
Then we say, if x is less then 50 (which it is), then it prints out
x is 20 (since x is i which is 20), else it will print out
x is <number that i holds>.

Not so very hard is it ?
-------------------------------------------------------------------------------
Now it's time to take a look at the for loop.
The first thing I need to say here is that i++ will increas i with 1,
let me illustrate this in a tiny code:

//----------------------------------------------------------
#include <stdio.h>
int main ( void )
{
int i;
i = ( 2 );
printf ("i is now %i\n", i);
i++;
printf ("i is now %i\n", i);
i++;
printf ("i is now %i\n", i);
return 0;
}

//----------------------------------------------------------
This will output the following:
i is now 2
i is now 3
i is now 4

This is very handy, I should also say that i--; will decrease i by 1.
But now on to an example with a for loop, make a file and call it forloop.c
and in it do the following:

//----------------------------------------------------------
#include <stdio.h>
int main ( void )
{
int i;

for ( i = 0 ; i < 10 ; i++ ) {
printf ( "i is now: %i\n", i );
}
return 0;
}
//----------------------------------------------------------
Let's see how this looks when it's executed.
alien:~$ gcc -o forloop forloop.c
alien:~$ ./forloop
i is now: 0
i is now: 1
i is now: 2
i is now: 3
i is now: 4
i is now: 5
i is now: 6
i is now: 7
i is now: 8
i is now: 9
alien:~$

-------------------------------------------------------------------------------
So now what does the code mean ?
First for works like this:
for ( ; condition ; ) { action }
So let's cut right to the new part:
....
for ( i = 0 ; i < 10 ; i++ ) {
printf ( "i is now: %i\n", i );
}
....

First let's take a look at what's inside the paranteses.
Three feilds separated by ; (semi colon)
"i = 0 ; i < 10 ; i++".
"i = 0", that's easy to know what it means. it set's i to be 0.
The next of the 3 feilds is "i < 10", this means that as long as
i is less then 10, it will perform the action.
And then the "i++" that will increase "i" for every time it loops.

So basically it will read what's inside paranteses over and over again
until it the condition is reached, each time performing the action.

In this code the condition will be met when i is no longer less then 10.
-------------------------------------------------------------------------------
Now here is another short example of a for loop, this time without the
surrounding code.

....
for (;;) {
printf ("This will go on forver\n");
}
....

I dont even need to explain this very much.
If you dont set any conditions at all, it will just keep on looping
for all eternety.

This can be very useful at times, like when coding daemons (servers)
that are suppose to do something over and over again all of the time.

-------------------------------------------------------------------------------
Now let's take a look at the scanf function.
scanf() is a function that will take something from stdin
(standard input - the keyboard), and use it in the code.

Let's illustrate it in an example.
Make a file called say scanftest.c and in it do this:

//----------------------------------------------------------
#include <stdio.h>
int main ( void )
{
char str[50];
printf ( "Type something: " );
scanf ( "%s", &str );
printf ( "You typed %s \n", str );
return 0;
}

//----------------------------------------------------------
Ok, so what does the new stuff here really do ?
First we create a pointer that we call str that can hold 50 characters.
The we print to screen (stdout - standard output) "Type something: ",
and after that we use scanf().

scanf ( "%s", &str );
This means that it scans %s (characters), and writes's them to str.
So why is there an amplersand (&) before the str ?

This is called to refference a pointer, you do that when you're writing
something to the actual location of where the pointer points to.
I will come back to that more later, for now just remember that this
is one of the places where you need to have an & before the pointer.

And then we print it out.
So, executed it could look like this:
alien:~$ gcc -o scanftest scanftest.c
alien:~$ ./scanftest
Type something: test
You typed test
alien:~$

-------------------------------------------------------------------------------
And that's all you need to know about the scanf function for now.
-------------------------------------------------------------------------------
Now let's take a look at argc and argv.
argc means argument counter and is an int, it will hold the number of arguments
passed on to the program. ( 3 arguments to a program is this ./program -o foo )
know that the program name it self is an argument in the 'mind' of argc.
arg means argument vector is is a char, and it will hold the actual
arguments passed to the program from the execution line.

So, in order to make this work, I said earlyer that the void in
"int main (void)" was there because we didnt pass anything on to the function,
but now we will, so here is an example, let's call the file program1.c:

//----------------------------------------------------------
#include <stdio.h>
int main ( int argc, char **argv )
{
if ( argc != 2 ) {
fprintf ( stderr, "Wrong number of arguments.\n" );
return -1;
}

printf ( "The argument was %s \n", argv[1] );
return 0;
}

//----------------------------------------------------------
Here are a few new things.
First:
int main ( int argc, char **argv )
This means that it will import argc as an int, argc was just explained.
and then we have argv as a char.
So why is there 2 *'s infront of argv ?
Well here a * infront of it means the same as a [] after it, some people
write it as "char *argv[]" personally I think that looks weird.
But perhaps the second way is more 'correct'.
Anyway, this means that argv[0], is argument 0, and hence the program name.
And argv[1], the first argument after the program name... and argv[2]
beeing the argument after that etc.

Then we have:
if ( argc != 2 ) {
This simply means, "if the argument counter not is two, then do .....".
And what does it do ?
This is also new.
fprintf ( stderr, "Wrong number of arguments.\n" );
fprintf means file print file, and the file that we are printing the message
to is stderr (/dev/stderr).
stderr is an abbreviation for standard error, with normal printf you print
by default to stdout which means standard output, and with scanf you read
from stdin, which is standard input... see the note below.
And why are you writing it out as stderr ?
One of the reasons is that if someone writes a shell script where your program
is called, they may expect errors and dont want them visible, and so they can
redirect the errors to /dev/null (the black hole of UNIX), but still see the
stdout if any appears.

And the next two lines after that:
return -1;
}

-1 means that it will return unsuccessful and quit.
Again one of the reasons for doing this is if somone does a shell script
that needs to know if the program was executed successfully or not.
And then close the if statement with the bracket.

And the next line .... you should be able to figure that one out:
printf ( "The argument was %s \n", argv[1] );
The normal printf you know, and the %s you know too by now.
But instead of a 'normal' pointer we use argv[1], argv is a pointer to
all the arguments, and the number inside the brackets says which of the
arguments it should be.

And then return with success and close the main function.
So basically, if it has the wrong number of arguments it will die and
tell you so, but in other cases it will ignore the action of the if statement
because the condition isn't met... and go right on to the printf line.

So, executed it could look like this:
alien:~$ gcc -o program1 program1.c
alien:~$ ./program1
Wrong number of arguments.
alien:~$

Or:
alien:~$ gcc -o program1 program1.c
alien:~$ ./program1 foo
The argument was foo
alien:~$

Or:
alien:~$ gcc -o program1 program1.c
alien:~$ ./program1 bar
The argument was bar
alien:~$

etc.
-------------------------------------------------------------------------------
I/O (Input / Output)
stdout - standard output (1)
stderr - standard error (2)
stdin - standard input

-------------------------------------------------------------------------------
Now let's take a short look at the strcmp function.
strcmp means string compare, and will compare two character strings,
(just two pointers works just as well, but here we will compare a pointer
with a pre made string).

So let's begin, open a file and call it strcmpex.c, and in it do:
//----------------------------------------------------------
#include <stdio.h>
int main ( int argc, char **argv )
{
if ( argc != 2 ) {
fprintf ( stderr, "Wrong number of arguments.\n" );
return -1;
}

if ( strcmp ( argv[1], "root" ) == 0 ) {
printf ( "argv[1] was root\n" );
}
else
{
printf ( "argv[1] was NOT root\n" );
}
return 0;
}

//----------------------------------------------------------
Now the only really new thing in here was this line:
if ( strcmp ( argv[1], "root" ) == 0 ) {
This will compare if argv[1] (the first argument after the program name),
and the word/string "root" returns success (that will only happen if they
are the same), and if so do the action.
If we instead would have said:
if ( strcmp ( argv[1], "root" ) != 0 ) {
That would have meant, if argv[1] and "root" does not match....

This should be understandeble, but just in case it isn't, there will be
be another explanation with an example shortly.

This time I will not show how this program looks executed, you gonna have
to test it your self, unless you already can deduct how it will look.

-------------------------------------------------------------------------------
So now let's take a short look at the atoi (ascii to integer).
atoi is really simple, and works like this:

....
int i;
char str[3];
sprintf ( str "5" );
i = ( atoi ( str ) );
....

And as you see, now the char that contains "5" as a character, is now
converted to an integer.
This will come to good use in a while.

Basicly, you could say that "atoi(str)" is used the same way as if
the char would have been a single int in the first place.

There is also atof (ascii to float) and atol (ascii to long) etc. but I'll
explain those later.

-------------------------------------------------------------------------------
Now let's make a little test program, just to see how a program that actually
has a purpose and makes use of what you know this far looks like.
So as a test example let's do a little very simple calculator.

So open a file, let's call it calc.c and in it type the following:
//----------------------------------------------------------
#include <stdio.h>
int main ( int argc, char **argv )
{
int i;

if ( argc != 4 ) {
fprintf ( stderr, "Usage: %s <int> <+|-|/|'*'> <int>\n", argv[0]);
return -1;
}

if ( strcmp ( argv[2], "+" ) == 0 ) {
i = ( atoi ( argv[1] ) + atoi ( argv[3] ) );
}

if ( strcmp ( argv[2], "-" ) == 0 ) {
i = ( atoi ( argv[1] ) - atoi ( argv[3] ) );
}

if ( strcmp ( argv[2], "/" ) == 0 ) {
i = ( atoi ( argv[1] ) / atoi ( argv[3] ) );
}

if ( strcmp ( argv[2], "*" ) == 0 ) {
i = ( atoi ( argv[1] ) * atoi ( argv[3] ) );
}

printf ( "The answer is: %i \n", i );
return 0;
}

//----------------------------------------------------------
Now let's see what we have done here:
Everything should be understandeble and clear, but just in case
you dont follow this to 100% I'll explain it again in detail.

First we include the standard input output header file.
#include <stdio.h>
Then we make a main function that may import the numbers of arguments as
an integer (int argc - argument counter), and the arguments them self
as characters / ascii, (char **argv - argument vector).

int main ( int argc, char **argv )
The we open the funciton with a bracket.
{

Then we declare i as an integer.
int i;
Then we ask if the argument counter is not 4.
if ( argc != 4 ) {
And if it's not 4 arguments (the program name is one of them),
then we print the following to stderr (the standard error output).

fprintf ( stderr, "Usage: %s <int> <+|-|/|'*'> <int>\n", argv[0]);
And after that we exit the program with status - unsuccessful.
return -1;
And then we close the "if" function.
}
And if the "if" function didnt exit us which it only happens if the argc
is others then 4, then the program goes on to the following.

Here we check if argv[2] is a "+".
if ( strcmp ( argv[2], "+" ) == 0 ) {
And if it is a plus, then it will count argv[1] + argv[3] (the argv's gets
converted to intgers with the atoi).

i = ( atoi ( argv[1] ) + atoi ( argv[3] ) );
And then we close that if function.
}

Next we check if argv[2] is a "-".
if ( strcmp ( argv[2], "-" ) == 0 ) {
And if it is a minus, then it will count argv[1] - argv[3].
i = ( atoi ( argv[1] ) - atoi ( argv[3] ) );
And then we close that if function.
}

Next we check if argv[2] is a "/".
if ( strcmp ( argv[2], "/" ) == 0 ) {
And if it is a slash (devided with), then it will count argv[1] / argv[3].
i = ( atoi ( argv[1] ) / atoi ( argv[3] ) );
And then we close that if function.
}

And last we check if argv[2] is a "*".
if ( strcmp ( argv[2], "*" ) == 0 ) {
And if it is a asterisk (times), then it will count argv[1] * argv[3].
i = ( atoi ( argv[1] ) * atoi ( argv[3] ) );
And then we close that if function.
}

After having the actual counting done, we print it out.
printf ( "The answer is: %i \n", i );
And then we exit with success.
return 0;
And finally we close the main funtion.
}

-------------------------------------------------------------------------------
The compiling:
alien:~$ gcc -o calc calc.c
This executed may look like this:
alien:~$ ./calc 12 + 23
The answer is: 35
alien:~$

Or:
alien:~$ ./calc 15 - 9
The answer is: 6
alien:~$

Or:
alien:~$ ./calc 44 / 3
The answer is: 14
alien:~$

Or:
alien:~$ ./calc 9 '*' 8
The answer is: 72
alien:~$

Note that the asterisk have to be within ` quotes, else it will expand as
a wildcard, and so wont work.

-------------------------------------------------------------------------------
Finally in this section, let's have a look at the strcpy() function.
strcpy() works a little like sprintf, to say:

strcpy( ptr, argv[0] );
Is the same as to say:
sprintf ( ptr, "%s", argv[0] );
So strcpy(), will copy the second character pointer to the first one.
Let's make a short example:
//----------------------------------------------------------
#include <stdio.h>
int main ( int argc, char **argv )
{
char ptr[256];

strcpy ( ptr, argv[0] );
printf ( "The program name of this program is: %s \n" , ptr );
return 0;
}
//----------------------------------------------------------
Now try this, and you'll understand it if you dont undersand it already.
-------------------------------------------------------------------------------
That was about all on the very first basics on C programming, at this point
you should play some and make silly little program that dont have any
real purpose, unless you have some great ideas.

1 - Where do I start

============================ Aliens C Tutorial ================================
-----------------Written by Alien <-> alien@ktv.koping.se----------------------
===============================================================================

First of all, this tutorial will be much more of a challange to write
then my previous tutorial (bash.tutor), in this tutorial I will try
to explain the C programming language and make it undestandeble.....
This tutorial will explain ANSI C,
(ANSI is American National Standards Institute).

C was first developed at Bell Labs by Brian W. Kernighan and Dennis M. Ritchie.
C is a programming language that needs to be compiled when written, this
is the oposit of shell scripting like bash.
C is ALOT more powerful then bash or any script language, with C you
have real controll over what your program will do.

C is developed for UNIX, and the examples in this tutorial is made to
work on UNIX, they should however also work in DOS, but I leav no
promices for that.

The code in this tutorial is written more or less only in K&R
(Kernighan and Ritchie) style C, this style is also called Bell Labs style.
Later I will explain the difference between the Bell Labs style and
student style.

I will not take up anything about graphical programming in this tutorial
for more then one reason, but the best is that it would take up to much
space and be confusing, so if you want to learn graphical programming in
C, read this tutorial to learn the actual language and then some other
tutorial about graphical programming, another reason is that there is
more then one way of doing graphical programming because there are
several sets of 'wigets' and libs that can do that.

I will try to start from the very beginning so here we go.

===============================================================================
1 - Where do I start ?
===============================================================================

You start here, with a simple "hello world" program.
Make a file called hello.c and in it do the following:

//----------------------------------------------------------
#include <stdio.h>
int main ( void )
{
printf ( "hello world!\n" );
return 0;
}

//----------------------------------------------------------
And once you've saved and exited, your ready to compile it,
and that you do like this:

gcc -o hello hello.c
Now you can execute it:
./hello
And it will look like this:
alien:~$ gcc -o hello hello.c
alien:~$ ./hello
hello world!
alien:~$

-------------------------------------------------------------------------------
So, now what have you done, and what does that mean ?
You have done your first program in C, that will output "hello world!"
to the screen.

So, now 'exactly' what does the code mean ?
Let's start from the first line.
#include <stdio.h>
This will include the header file stdio (standard input output), this file
holds the information on how, among others, the printf function works and
how it should be handeld by the compiler.
I will explain header files better later.

The next after that is:
int main ( void )
This makes a function called main, which is the core function of your code
that can call for other functions later.
main is always of type 'int' (integer), because it has to 'return' something to
the system, I will come to that very shortly.
And the ( void ) part means that we will not pass any arguments to the main
function.
You dont really have to know what all this means at this point, but I'm still
telling it so you will have an easyer time understanding it later.

The next line after that is the:

{
This opens the function, and expects an action.
The next line after that is:
printf ( "hello world!\n" );
This is the main action in our program.
Here we print 'hello world!' to the screen, the \n means new line.

printf is a function, and as any funtion it's arguments is written inside
the paranteses, and the line is ended/terminated with a semi-colo.

The next line is:
return 0;
Here we return 0 to the system, this means success, and the program know's
that it has finished successfully here.
0 means successful, and -1 means unsuccessful.

And the last line:
}
This closes your function.
-------------------------------------------------------------------------------

Note: return 0; can also be written as: return ( 0 );
-------------------------------------------------------------------------------
So what do you need to remember about this at this point ?
Well, the thing that you need to remember is the basic layout for a
program.

#include <stdio.h>
int main ( void )
{

  return 0;
}

So memorize that for the time beeing.
-------------------------------------------------------------------------------
So next up ?
Now it's time to explain integers and how to count in C, so here we go.
Make a file called count.c and in it do the following:

//----------------------------------------------------------
#include <stdio.h>
int main ( void )
{
int i, x;

  i = ( 50 );
x = ( i + 10 );
printf ( "x is now: %i \n", x );
return 0;
}

//----------------------------------------------------------
And once you've saved and exited, your ready to compile it,
and that you do like this:

gcc -o count count.c
And now you can execute it by doing:
./count
And it will look like this:
alien:~$ gcc -o count count.c
alien:~$ ./count
x is now: 60
alien:~$

-------------------------------------------------------------------------------
So, now what have we done this time, and what does that mean ?
The 3 first lines is (I hope) already well explained.

So the fist new line here is:
int i, x;
This tells the program that there is 2 variables (separated by a comma),
that are of type integer, all pointers and variables must be declared
before any real action in the code.
Exactly what a pointer is I will explain after the next example.
A variable is just a name that can hold data inside it ...
That's not the best explanation, but that's a good way of thinking about it.
It really works about the same a pointer, but just think of it as a
synonyme or a rename of a value.
These 2 integer variables can hold data that is integer numbers.

Which is shown in the next line:
i = ( 50 );
Here we make the integer variable i hold the value 50.
And the next line:
x = ( i + 10 );
Here we make the int x hold the value of i (50) plus 10, which
is 60.

The next line after that we print the resault out to the screen:
printf ( "x is now: %i \n", x );
The new things here is the %i which tells printf to replace that space
with an integer that's held in a variable that comes after the a comma
after the double quote, this will be shown better in later examples.

And the return 0; and the close bracket is already explained.
-------------------------------------------------------------------------------
Next up is almost the same as the previous example, but this time with
characters instead of integers.

So here we go with an example of character pointers.
Make a file called string.c and in it do the following:

//----------------------------------------------------------
#include <stdio.h>
int main ( void )
{
char ptr[10];
sprintf ( ptr, "My String" );
printf ( "ptr contains: %s \n", ptr );
return 0;
}

//----------------------------------------------------------

And once you've saved and exited, your ready to compile it,
and that you do like this:

gcc -o string string.c
And now you can execute it by doing:
./string
And it will look like this:
alien:~$ gcc -o string string.c
alien:~$ ./string
ptr contains: My String
alien:~$

-------------------------------------------------------------------------------
So, now what have we done now, and what does that mean ?
As before the first 3 lines you should know now.
And then there is the next new line that looks like this:

char ptr[10];
This declares a pointer that will hold data of type char (characters),
and the [10], means that it will hold the room for max 10 characters.

The next new line in the code is this:
sprintf ( ptr, "My String" );
sprintf means string print file, and the pointer is before the static text,
because this time we are pointing the pointer to a string and not displaying
it like to the screen like we did with the integers in the last example.
In short, sprintf will point a point 'to' the string.
(pointers will be explaind under this example).

But that we do here instead:
printf ( "ptr contains: %s \n", ptr );
This works the same as with the integers but we have to use %s to tell
printf that it's suppose to write it out as characters.

And the 2 last lines you should know by now.
-------------------------------------------------------------------------------
So exactly what is a pointer ?
I will try to be breaf about this, and you dont really need to remember this,
I'm putting it here for the sake of the knowlidge and that you should atleast
have read it at some time .... so now is a time as good as any.

Here we have a chunk of memory in the computer:
  1   2   3   4   5   6   7   8   9  10  11  12
-------------------------------------------------
|   |   |   |   |   |   |   |   |   |   |   |   |
-------------------------------------------------

This is a chunk of memory that has 12 bytes.
And if we do:

char pointer[6];
It will resault in this:
  1   2   3   4   5   6   7   8   9  10  11  12
-------------------------------------------------
|   |   |   |   |   |   |   |   |   |   |   |   |
-------------------------------------------------
^                     ^
|_____________________|
|
|------ pointer

So you see, that's why it's called a pointer, because it points to a
chunk of memory, and if we write something to it, by doing say:

sprintf ( pointer, "String" );
The memory will look like this:
  1   2   3   4   5   6   7   8   9  10  11  12
-------------------------------------------------
| S | t | r | i | n | g |   |   |   |   |   |   |
-------------------------------------------------
^                       ^
|_______________________|
|
|------ pointer

This is why you need to declare a pointer, so it can point to a free space
in the memory, of the size of your choice, where it can store it's data.

I hope that this explains how a pointer works.
-------------------------------------------------------------------------------
Here is an example with both characters and integers.
Make a file called intstring.c and in it do the following:

//----------------------------------------------------------
#include <stdio.h>
int main ( void )
{
int i, j, x;
char ptr[10];

  sprintf ( ptr, "My String" );
i = ( 3 );
j = ( 7 );
x = ( i + j );
printf ( "ptr contains: %s \nAnd x contains: %i \n", ptr, x );
return 0;
}

//----------------------------------------------------------
And once you've saved and exited, your ready to compile it etc.
And it will look like this:
alien:~$ gcc -o intstring intstring.c
alien:~$ ./intstring
ptr contains: My String
And x contains: 10
alien:~$

-------------------------------------------------------------------------------
This time you should know what we have done.
But just in case, I'll explain it anyway.

First we inlude the standard input/output header file.
Then we create a main function with nothing to pass to it, (the void).
Then we open the function.
After that we declare i, j and x as integers.
And then declare ptr as a char pointer that may hold 10 bytes.
After that we print "My String" to the memory location of the ptr pointer.
Next we say that i should be a 3, j a 7 and x should hold i + j,
which means 3 + 7.
And then we print it out to the screen.
If you look at the line where we print it out to the screen:

printf ( "ptr contains: %s \nAnd x contains: %i \n", ptr, x );
Now if we were to print out the integer first and the string after that,
the line would have looked like this:

printf ( "x contains: %i \nAnd ptr contains: %s \n", x, ptr );
Notice that you also have to switch places for the pointers after the
double quote.

After that we have the return 0; which tells the system that it's come to
this point successfully and that it will quit here.
And then we close the main function.

-------------------------------------------------------------------------------
Note: printf with pointers works like this:
printf ("char 1 %s - char 2 %s - char 3 %s etc.", char1, char2, char 3);

-------------------------------------------------------------------------------
Now it's time to start to comment the code.
To make memory notes so you know what you have done for later.
This is something all coders does.

Let's take the last code,  intstring.c and comment it.
//----------------------------------------------------------
#include <stdio.h>
int main ( void )
{
/* declare variables and pointers */

  int i, j, x;
char ptr[10];

  /* print the string to the memory location
* that the pointer ptr points to.
*/

  sprintf ( ptr, "My String" );
  /* point the integers to something */
  i = ( 3 );
j = ( 7 );
x = ( i + j );

  /* print it out to the screen */
  printf ( "ptr contains: %s \nAnd x contains: %i \n", ptr, x );
  /* return success and exit. */
  return 0;
}

//----------------------------------------------------------
Now normally you dont comment *everything* in a code like this,
but you may wanna comment things in your codes so that you can remember
what you have done and to make it easyer to search, and if not for that,
to make it readeble to others, if you are in a coding team.

The /* starts a comment and */ ends a comment in C, and if you have several
lines you do like this:

/* here is
* a comment
* that's
* severa lines
*/

You may also come across comments that are made with 2 slashes like this: //
That is really a C++ comment and will comment out the rest of the line
from that point.
It can be used like this:

printf ( "Anything here\n"); // print something to the screen
But a real C comment should look like this:
printf ( "Anything here\n"); /* print something to the screen */
Note that they both work in C and C++, but it's standard to use the /**/ in C
and the // in C++.

-------------------------------------------------------------------------------
That was the very start to begin to learn C, this following section
will be a little bit harder, but still basics.