+ All Categories
Home > Documents > An Introduction to C Programming

An Introduction to C Programming

Date post: 20-Jan-2016
Category:
Upload: azura
View: 25 times
Download: 0 times
Share this document with a friend
Description:
An Introduction to C Programming. (assuming that you already know Java; this is not an introduction to C++). Minimal C program. int main ( int argc, char** argv ) { return 0; //comment just like Java } Or int main ( int argc, char* argv[] ) { return 0; /* comment just like Java */ } - PowerPoint PPT Presentation
52
An Introduction to An Introduction to C Programming C Programming (assuming that you already know Java; this is not an introduction to C++)
Transcript
Page 1: An Introduction to C Programming

An Introduction to C An Introduction to C ProgrammingProgramming

(assuming that you already know Java;this is not an introduction to C++)

Page 2: An Introduction to C Programming

Minimal C programint main ( int argc, char** argv ) {

return 0; //comment just like Java}

Or

int main ( int argc, char* argv[] ) {return 0; /* comment just like Java */

}

Or (typically, you aren’t going to change them)

int main ( const int argc, const char* const argv[] ) {return 0;

}

What does main look like in Java?What is used as ‘const’ in Java?

Page 3: An Introduction to C Programming

Java’s main

public static void main ( String args[] ) {

}

Page 4: An Introduction to C Programming

C vs. Java types

• C– doesn’t init vars (with

a few exceptions)

– bool, char, short, int, long

– float, double– unsigned char– unsigned short– unsigned int– long long– long double

• Java– does init vars

(specifically objects which are defined to be an instance of a class OR arrays; primitive types are NOT initialized and require initialization)

– boolean, byte, short, int, long

– float, double

Page 5: An Introduction to C Programming

ASCII output in C (using the standard I/O library)

#include <stdio.h> //needed for defns

int main ( int argc, char* argv[] ) {puts( “hello, world.” );printf( “hello, world.” );printf( “hello, world.\n” );return 0;

}

Page 6: An Introduction to C Programming

ASCII output in C#include <stdio.h> //header file w/ definitions

int main ( int argc, char* argv[] ) {printf( “hello, %s. \n”, “fred” );

int i = 12;printf( “I am %d years old. \n”, i );

double d = 12.9;printf( “d is equal to %f (d is not equal to %d). \n”,

d, d );

return 0;}

How can d be both %f and %d?

Page 7: An Introduction to C Programming

ASCII file output in C (using the standard I/O library)

#include <assert.h>#include <stdio.h>

int main ( int argc, char* argc[] ) {//open the file for output (erase anything already there!)FILE* fp = fopen( “fred.dat”, “wb” );assert( fp!=NULL );

//write to the filefprintf( fp, “hello, world.\n” );

//close the filefclose( fp );fp = NULL;

return 0;}

Hint: Always open b/binary or binary I/O will act strangely under Windows.

Page 8: An Introduction to C Programming

ASCII file output format specs

• %d – an int

• %c – a char

• %x – an int in hex

• %f – a double or a float

• %s – string

• Many, many, many others and variations.

Page 9: An Introduction to C Programming

ASCII file input format specs

• %d – an int

• %c – a char

• %x – an int in hex

• %f – a float

• %lf – a double (that’s % ell eff)

• %s – string

• Many, many, many others and variations.

Page 10: An Introduction to C Programming

Binary file output in C

• We will discuss binary file I/O after we discuss pointers.

• We will discuss input after we discuss pointers as well.

Page 11: An Introduction to C Programming

I/O in C

• printf, scanf, gets, and puts perform buffered I/O (to stdin and stdout).

• fopen, fread, fwrite, fprintf, fseek, fscanf, fgets, fputs, and fclose perform buffered I/O.

• open, read, write, seek, and close perform unbuffered I/O.

Page 12: An Introduction to C Programming

C pointers int i=12;

– i is a variable. It exists in some memory location. At that memory location is the value of 12.

– What is the size of i (in bytes)?printf( “An int is %d bytes. \n”, sizeof(int) );

printf( “i=%d, i occupies %d bytes. \n”,

i, sizeof(i) );

– What is the virtual address of i, i.e., where is i in memory?

Page 13: An Introduction to C Programming

C pointers

Let’s introduce an operator (&) that yields the address of a variable.

int i = 12;

printf( “the address of i is %d. \n”, &i );

printf( “the address of i is %x. \n”, &i );

Page 14: An Introduction to C Programming

C pointers

How do we declare variables that hold pointers (instead of values)?

int i=12, j=52;

int* ptr = &i; //ptr points to i

ptr = &j; //ptr now points to j

Page 15: An Introduction to C Programming

C pointers

Derefencing pointers (getting at what they point to):

int i = 12;

int* iptr = &i;

printf( “i=%d, *iptr=%d. \n”, i, *iptr );

Is *iptr the same as iptr?

Page 16: An Introduction to C Programming

C pointers

Derefencing pointers (getting at what they point to):

int i = 12;

int* iptr = &i;

*iptr = 52;

printf( “i=%d. \n”, i ); //What is i’s value?

Page 17: An Introduction to C Programming

C pointers

• C pointers can be treated as arrays.

#define N 100

int ray[ N ];

int* ptr = ray; //same as ptr=&ray[0]

for (int i=0; i<N; i++) {

ptr[i] = 0; //same as ray[i] = 0

}

Page 18: An Introduction to C Programming

C pointers

• C pointers can be treated as arrays.

#define N 100

int ray[ N ];

int* ptr = ray; //same as ptr=&ray[0]

for (int i=0; i<N; i++) {

*ptr = 0;

++ptr;

}

Page 19: An Introduction to C Programming

C pointers

• C pointers can be treated as arrays.

#define N 100

int ray[ N ];

int* ptr = ray; //same as ptr=&ray[0]

for (int i=0; i<N; i++) {

*ptr++ = 0;

}

Page 20: An Introduction to C Programming

C pointers

• C pointers can be treated as arrays (most of the time).

#define N 100int ray[ N ];int* ptr = ray; //same as ptr=&ray[0]for (int i=0; i<N; i++) {

*ptr++ = 0;}

Every time we ++ ptr, how much is added to ptr? 1?

Page 21: An Introduction to C Programming

C pointers

• Common pitfall

int* ptr1, ptr2; //what (type) is ptr2?

Page 22: An Introduction to C Programming

C pointers

• Common pitfall

int* ptr1, ptr2;

This is actually the same as

int *ptr1, ptr2;

Which means that ptr2 is an int (not an int*)!

Page 23: An Introduction to C Programming

C pointers and arrays

• Common pitfall

#define N 100

int ray[ N ];

int* ptr = ray;

printf( “%d %d \n”, ray[N], ptr[1000] );

Page 24: An Introduction to C Programming

C pointers and arrays

• Common pitfall

#define N 100

int ray[ N ];

int* ptr = ray;

printf( “%d %d \n”, ray[N], ptr[1000] );

Page 25: An Introduction to C Programming

More C pointers

Cast = change from one type to another.

double d = 0.7;int i = (int)(d+0.5); //round dint j = (int)d; //don’t round d

Sometimes we need to change (cast) from one pointer type to another.

Page 26: An Introduction to C Programming

ASCII input

Use scanf (from stdin) and fscanf.

printf( “enter two integers: “ );

int n1, n2;

scanf( “%d %d”, &n1, &n2 );

Why is ‘&’ necessary?

Page 27: An Introduction to C Programming

ASCII input

Use fscanf to read from ASCII files.

FILE* fp = fopen( “input.txt”, “rb” );assert( fp!=NULL );int n1, n2;fscanf( fp, “%d %d”, &n1, &n2 );…How do we know if anything was

read?

Page 28: An Introduction to C Programming

How do we know if anything was read?

int scanf ( const char *format, ... );

int fscanf ( FILE *stream,

const char *format, ... );

Page 29: An Introduction to C Programming

ASCII input

Use fscanf to read from ASCII files.

FILE* fp = fopen( “input.txt”, “rb” );

assert( fp!=NULL );

int n1, n2, count;

count=fscanf( fp, “%d %d”, &n1, &n2 );

if (count!=2) {

}

Page 30: An Introduction to C Programming

Notes about I/O

• stdin, stdout, and stderr are predefined for you and available for every program to use.

– You do not need to define them and you should not open them.

– They are already defined for you when you #include <stdio.h>.

Page 31: An Introduction to C Programming

More notes about I/O

fprintf( stdout, “hello \n” );is the same as

printf( “hello \n” );

scanf( “%d”, &n1 );is the same as

fscanf( stdin, “%d”, &n1 );

Page 32: An Introduction to C Programming

More notes about I/O

• Read in a line of input.char *gets ( char *s );

char *fgets ( char *s, int size, FILE *stream );

– What’s the difference between:char buff[ 255 ];

gets( buff ); andfgets( buff, sizeof(buff), stdin );

Page 33: An Introduction to C Programming

More notes about I/O

What’s the difference between:char buff[ 255 ];

gets( buff ); andfgets( buff, sizeof(buff), stdin );

gets: “Reads characters from stdin and stores them as a string into str until a newline character ('\n') or the End-of-File is reached. The ending newline character ('\n') is not included in the string. A null character ('\0') is automatically appended after the last character copied to str to signal the end of the C string.

Notice that gets does not behave exactly as fgets does with stdin as argument: First, the ending newline character is not included with gets while with fgets it is. And second, gets does not let you specify a limit on how many characters are to be read, so you must be careful with the size of the array pointed by str to avoid buffer overflows.”

from http://www.cplusplus.com/reference/clibrary/cstdio/gets/

Page 34: An Introduction to C Programming

More C pointers

• Dynamic memory allocation (and deallocation).– malloc

int* iptr = (int*)malloc( 10*sizeof(int) );

assert( iptr!=NULL );

– freefree( iptr );

iptr = NULL; //good idea, not required

• Must #include <stdlib.h> at top.

cast

Page 35: An Introduction to C Programming

Binary I/O

• Buffered– fread and fwrite

• Unbuffered– read and write– We will skip unbuffered I/O (but

you are free to use it).

Page 36: An Introduction to C Programming

Binary input: fread

size_t fread ( void* ptr, size_t size,

size_t nitems, FILE* stream );

• Returns nitems if OK.

FILE* fp = fopen( “junk.in”, “rb” );

#define N 100

int buffer[ N ];

int k = fread( buffer, sizeof( int ), N, fp );

• What is k?

Page 37: An Introduction to C Programming

Binary input: fread

size_t fread ( void* ptr, size_t size,

size_t nitems, FILE* stream );

• Returns nitems if OK.

#define N 100

int buffer[ N ];

int k = fread( buffer, sizeof( int ), N, fp );

k = fread( buffer, 1, sizeof( buffer ), fp );

k = fread( buffer, sizeof( buffer ), 1, fp );

Page 38: An Introduction to C Programming

Binary input: fread

int buffer[ N ];

int k = fread( buffer, 1, sizeof( buffer ), fp );

k = fread( buffer, sizeof( buffer ), 1, fp );

This (sizeof(buffer)) is an example of where arrays and pointers are NOT the same in C!

Page 39: An Introduction to C Programming

Binary output: fwrite

size_t fwrite ( void* ptr, size_t size,

size_t nitems, FILE* stream );

• Returns nitems if OK.

FILE* fp = fopen( “junk.in”, “wb” );

#define N 100

int buffer[ N ];

int k = fwrite( buffer, sizeof( int ), N, fp );

• What is k?

Page 40: An Introduction to C Programming

0utput in C (using the standard C++ library)

#include <iostream>

using namespace std;

int main ( int argc, char* argc[] ) {cout << “hello, world.” << endl;return 0;

}

You are free to use the standard C++ library but we won’t discuss it in this class.

Page 41: An Introduction to C Programming

C structs (structures)

• Collection of data (only).– precursor to objects– similar to a FORTRAN record

• Especially useful for message passing.– Ex. { do this operation, here is the

data }

Page 42: An Introduction to C Programming

C structs (structures)

struct message {enum { OP_CALCULATE,

OP_RESULT,OP_EXIT };

int operation;int parameters[100];double result;

};Tip: don’t forget ;

Page 43: An Introduction to C Programming

C structures

int main ( int argc, char* argv[] ) {

struct message m;

m.operation = m.OP_CALCULATE;

return 0;

}

Page 44: An Introduction to C Programming

C structures (w/ pointers)

int main ( int argc, char* argv[] ) { struct message* m; m = (struct message*) malloc (sizeof(struct message) ); assert( m!=NULL );

m->operation = m->OP_CALCULATE; //most often used

(*m).operation = (*m).OP_CALCULATE; //same thing

return 0;} Why not sizeof(struct

message*)?

Page 45: An Introduction to C Programming

C++ classes (not required for this course)

class Simple3D : public DistanceTransform3D { public:

//define public members (data) and methods (functions) here...

private:...

protected:...

};

Page 46: An Introduction to C Programming

Useful header files

#include <assert.h>

#include <stdio.h>

#include <stdlib.h>

Page 47: An Introduction to C Programming

Compiling C/C++ programs on Linux

• g++ compiles both C and C++– Always use g++ for C or C++.

• (Don’t use gcc. It only compiles C and C programs that compile with gcc may not compile with g++.)

• g++ won’t compile 1978 K&R C code but you shouldn’t be coding in that anyway.

• File name extensions– Always use .cpp for C or C++.

• (Don’t use .c. It is only for C programs which may compile with gcc but not with g++.)

• Enter ‘man g++’ for help.

Page 48: An Introduction to C Programming

Compiling and running C programs on Linux

g++ command options-g, -O, -O2, -O3

• Optimization level – debug to optimized.-c

• Compile (making a .o file) but don’t link.-o

• Specify output file name.-l

• (el=lower case L) Specify link library name.

Note: use mpic++ to compile mpi-based C/C++ programs.

Page 49: An Introduction to C Programming

Example of compiling C programs

g++ junk.cpp• Compile and link producing a.out.

g++ -c junk.cpp• Compile (but don’t link) producing

junk.o.

g++ -o junk.exe junk.o• Link junk.o and produce junk.exe.

g++ -o junk.exe junk.cpp• Compile and link producing junk.exe.

Page 50: An Introduction to C Programming

Example of compiling C programs

g++ -g -o junk.exe junk.cpp• Compile and link producing junk.exe w/ debug

information.

g++ -O3 -o junk.exe junk.cpp• Compile and link producing an optimized version

called junk.exe.

g++ -O -o fred.exe junk1.cpp junk2.o \ junk3.cpp -lm

• Compile junk.1pp and junk3.cpp (but not junk2.o) and link producing fred.exe which is somewhat optimized and linked to the math library.

Page 51: An Introduction to C Programming

Handling C command line arguments

• argc– count/number of arguments

• argv– array of strings (the actual arguments)

• Java doesn’t have argc. Why?• In Java, argv[0] is the first argument.

In C, argv[0] is the name of the program/command and argv[1] is the first argument.

Page 52: An Introduction to C Programming

End of C for Java programmers


Recommended