C Programming

Class 2


Objective

Download the examples c2.tar

Arrays

An array is a group of memory locations related by the fact that they all have the same name and same type.

Declaring Arrays

int c[12];

This tells the computer to reserve 12 elements for the integer array c. Other examples are:

float a[100], b[23];
char strng[256];
 

Using Arrays

ex1.c

Consider:
    int a[5] = {12, 5, 7, 11, 13};

The following table shows that all elements of the array share the same name a but each element has a different position number.

a[0]

a[1]

a[2]

a[3]

a[4]

12

5

7

11

13



Example

 

#include <stdio.h>

main()

{

float myarray[10];

int i;

myarray[0]=1;

for(i=1;i<10;i++)

        {

         myarray[i]=myarray[i-1]*(i+1);

        }

 

for(i=0;i<10;i++)

        {

        printf("%f\n",myarray[i]);

        }

}


String and Arrays

ex2.c

    A string in C is an array of characters ending in the NULL character ( '\0' ). Very similar to numeric arrays we can also declare an array of characters (char).

    The declaration:

    char sentence[80];

creates an array of 80 characters. It is important that when creating a string that you have enough space in the array to include the NULL character.

   A String constant is a sequence of zero or more characters surrounded by double quotes, for example:
char store[] = "I am a string";
Note: the size of this array is not specified, when the program is excuted, system will allocate enough space in memory to hold this string constant.

Several functions to manipulate character arrays.

ref of string.h

Remarks: The strcpy function copies strSource, including the terminating NULL character, to the location specified by strDestination. No overflow checking is performed when strings are copied or appended. The behavior of strcpy is undefined if the source and destination strings overlap.
 

Remarks: The strcat function appends strSource to strDestination and terminates the resulting string with a NULL character. The initial character of strSource overwrites the terminating NULL character of strDestination. No overflow checking is performed when strings are copied or appended. The behavior of strcat is undefined if the source and destination strings overlap.

#include <string.h>
#include <stdio.h>
void main( void ) {
    char string[80];
    strcpy( string, "Hello world from " );
    strcat( string, "strcpy " );
    strcat( string, "and " );
    strcat( string, "strcat!" );
    printf( "String = %s\n", string );
}

Output :
Hello world from strcpy and strcat!

Remarks: Each of these functions returns the number of characters in string, not including the terminating NULL character.

#include <string.h>
#include <stdio.h>
void main( void ) {
    char buffer[61] = "How long am I?";
    int len;
    len = strlen( buffer );
    printf( "'%s' is %d characters long\n", buffer, len );
}
 

Output:
'How long am I?' is 14 characters long

For more functions, try command:   man string


 

File I/O

 

C File Handling - File Pointers

C communicates with files using a new datatype called a file pointer. This type is defined within stdio.h, and written as FILE *. A file pointer called output_file is declared in a statement like

 
  FILE *output_file;

 

 

Opening a file pointer using fopen

Your program must open a file before it can access it. This is done using the fopen function, which returns the required file pointer. If the file cannot be opened for any reason then the value NULL will be returned. You will usually use fopen as follows

FILE * fopen ( const char * filename, const char * mode );
The first argument specifies the file name, the second argument specifies a file access modes. It can be:

               r  Open file for reading

               w” Open file for writing

               a Open file for appending

Closing a file using fclose

The fclose command can be used to disconnect a file pointer from a file. This is usually done so that the pointer can be used to access a different file. Systems have a limit on the number of files which can be open simultaneously, so it is a good idea to close a file when you have finished using it.

This would be done using a statement like

 
  fclose(output_file);

If files are still open when a program exits, the system will close them for you. However it is usually better to close the files properly.

fprintf and fscanf

The fprintf and fscanf command are very similar with printf and scanf, see printf for more details .

An example

ex3.c
Input file infile
question:
where is the output file?
if you use "mv infile inf" to change the file name, what will happen after compiling and running the code?
in the 6 line, change outfile[] = "outfile" into outfile[]="/outfile" what will happen after compiling and running the code?

Structures

A structure is a collection of variables under a single name. These variables can be of different types, and each has a name which is used to select it from the structure. A structure is a convenient way of grouping several pieces of related information together. A structure type is usually defined near to the start of a file using a typedef statement. It can be used throughout the program. See the following example
ex4.c
ex5.c
Input file for the above examples stfile


Note: These web pages were written with the reference text The C Programming Language by Brian W.Kernighan & Dennis M. Ritchie

Note2: The part of this web page referring to file i/o is from http://www.strath.ac.uk/IT/Docs/Ccourse/