C for the C++ or Java programmer
A C program contains:
- Include statements
#include <stdio.h>
#include "myfile.h"
- Defined Constants
#define MAXSTRINGSIZE 10
- Global Variables
int n;
char * myString;
- Functions
int increment(n)
{
return n+1;
}
- One "main" function
int main(int argc, char * argv[])
{
printf("Hello there!\n");
}
A C program does not contain:
- Classes
- Call functions, not methods
- Use a struct to group data:
typedef struct STUDENTRECORD {
int class;
char * name;
} studentRecord;
- Pass integers, floats, and pointers as parameters
- import statements (from Java)
- Constant types
- String types
- Operator overloading
- All operators have a predefined function
- Polymorphism
- Only one function of each name is allowed
- "new" and "delete"
- Instead memory management is done with "malloc" and "free"
- Stream operators "<<" and ">>"
- Use
printf() to print to stdout
- Use
sprintf() to print into a string
- Use
fprintf() to print to a file or stream
- Use
fgets() to read from a file or stream (such as stdin)
- try-catch-throw style exception handling
The main function and its input parameters
- The function
main() is called upon program invocation
- A typical
main() function is declared as follows:
int main (int argc, char * argv[])
- The parameter
argv contains an array of strings
- The first string is the name of the program
- Subsequent elements of this array are the input parameters to the program
- The parameter
argc contains the number of strings in argv
Variable Declarations
- All local variables must be declared at the beginning of a function,
before any statements
- Pointer variables are declared with an asterisk
int * myArray;
- Declaring a pointer only allocates space for the pointer, it does not allocate any space for the integer that is pointed to by this pointer.
Memory Management
- When dealing with strings, structs, arrays or any type that uses a
substantial amount of memory, memory management must be handled with
the malloc and free functions
malloc() allocates a block of memory of the specified
size and returns a pointer to that block.
- Normally the size is specified as "number of elements" multiplied by "size of one element"
malloc(MAXARRAYSIZE * sizeof(int));
- The return value is a void pointer so normally it should be cast to the correct type
myArray = (int *) malloc(MAXARRAYSIZE * sizeof(int));
- Memory is released using
free().
free(myArray);
Strings
- A string is declared as char array
char myString [100];
- Often this array is initially just a pointer, which is later alloced to the appropriate size using malloc
char * myString;
myString = (char *) malloc (MAXSTRINGSIZE * sizeof(char));
- There are many functions to manipulate strings. Read about the folowing functions in the man pages:
strlen() - returns the length of a string
strcat() - concatenates one string onto anther
strcpy() - copys one string into another
I/O
- Print out a string using
printf
printf("There are %d pieces of %s left\n", num, foodtype);
printf() takes a format string as the first parameter and a sequence of inputs as the remaining parameters.
- The format string can contain:
- Text
- Special characters
"\n" - newline
"\t" - tab
- ... and others
- Format characters which format the parameters
"%d" - integer parameter
"%g" - float parameter
"%s" - string parameter
- ... and others
File I/O
- Files begin as File pointers
- Open a file with
fopen()
myFile = fopen("filename.txt","r");
fopen takes the filename as the first parameter and a code indicating the type of file operations as the second parameter. The codes are:
"r" - Read Only
"w" - Rewrite over the existing file
"a" - Append to the existing file
- Additional codes can be found on the man page
- Usually you should check the return code of fopen for errors
if ((myfile = fopen(filename,"r")) == NULL) {
printf("Error opening %s\n",filename);
}
- Read and write using
fprintf and fgets
fprint(myFile,"This is line %d of your file",n);
fgets(myFile,myString);
A sample C file
fact0.c
- Compile this with:
g++ -o fact0.x fact0.c
- We get the following error:
fact0.c: In function `int getInt()':
fact0.c:25: implicit declaration of function `int malloc(...)'
fact0.c:32: implicit declaration of function `int atoi(...)'
- We can read the man pages for malloc and atoi from the Unix command line:
man malloc
man atoi
- The man pages tell us that we need to add
#include <stdlib.h> to the beginning of our C program
- The modified file, fact1.c compiles without error
- We see the following if we run the program and input 5:
Enter the value:5
You entered 5
The factorial of 5 is 0
- The program is giving the wrong output. Thus we need to use a debugger, such as GDB.
GDB
Step 1: Compile your program with -g option
g++ -g -o fact1.x fact1.c
Step 2: Start GDB
gdb fact1.x
Step 3: List the suspicious function
(gdb) list computeFact
35 }
36
37 // This function calculates the factorial of n and returns it
38
39 int computeFact(int n)
40 {
41 int accum=0;
42
43 while(n>1) {
44 accum *= n;
Step 4: Set a breakpoint at an appropriate line
(gdb) break 41
Breakpoint 1 at 0x120001938: file fact1.c, line 41.
Step 5: Run the program up to the breakpoint
(gdb) run
Starting program: /a/lamarck.cs.dartmouth.edu/usr/toe/grad/dwagn/cs58/clecture/fact1.x
Enter the value:5
You entered 5
Breakpoint 1, computeFact__Fi (n=5) at fact1.c:41
41 int accum=0;
Step 6: Display the suspicious variable
(gdb) display accum
1: accum = 1
Step 7: Step through the program while monitoring the variable
(gdb) step
43 while(n>1) {
1: accum = 0
(gdb)
44 accum *= n;
1: accum = 0
(gdb)
45 n--;
1: accum = 0
(gdb)
43 while(n>1) {
1: accum = 0
(gdb)
44 accum *= n;
1: accum = 0
(gdb)
45 n--;
1: accum = 0
Step 8: Evaluate the problem and fix it
Change
int accum=0;
to
int accum=1;
The new program, fact2.c runs correctly
Enter the value:5
You entered 5
The factorial of 5 is 120
Webpage maintained by David Wagner dwagn@cs.dartmouth.edu