Presentation Transcript
Play with C :Play with C For Programmers
Play with C :Play with C Why C now?
Try programming in a different language
Everything you do in Java (or other O-O language) can also implemented with C
See the real world - learn to deal with pointers.
Direct memory operation
Abundant Internet resources on C
“Learning C from Java”
“C language tutorial”
A good practice – part I, project 3
A Simple c program – “hello.c” :A Simple c program – “hello.c” /*---- Hello World C Example ("hello.c") -------------------------------------*/
/* ANSI C Headers */
#include
#include
/* Main Program starts here */
void main( )
{
int i = 0;
/* End of declarations ... */
for ( i = 0; i < 10; i++ )
{
printf( "%d Hello World ! \n", i ); /* print to standard output */
}
} Include headers if you need to use functions in these files Declare all your variables first Comment: /* .. */ NOT //
Compile C program :Compile C program Obtain a C compiler
Linux/Unix (suggested! use your CS account)
Usually c compiler is already installed
Windows 2000/XP
Microsoft Visual Studio has c compiler
Downloadable Free GNU c compilers
e. g. http://csjava.occ.cccd.edu/~gilberts/mingw/
Compiling a single-source C program in Unix (use cc, gcc, or g++ )
e.g.
cc –o hello hello.c
- An executable file named “hello” will be generated.
- “ cc hello.c “ is also okay. The output file will be named as “a.out”. cc –o
Run C program :Run C program Running the resulting program
Just type the name of the executable file. e.g.
hello
If you local directory is not included in “PATH”,
./hello
More details on C compilation and running
http://users.actcom.co.il/~choo/lupg/tutorials/c-on-unix/c-on-unix.html
Arrays in C :Arrays in C Array can be created with any type
int a[5]; /* use a[0], a[1], .., a[4] */
char b[3] ; /* use b[0], b[1], b[2] */
float c[2] = { .1, .2}; /*initialization at declaration. c[0] = 0.1 , c[1]=0.2 */
double c[3][5]; /* two dimensional array (column major as Java) */
Array starts at 0. There is no boundary checking.
Value of an array variable is the memory address of the first element.
Character arrays can be used as strings
char str[5];
strcpy(str, “hello”); /* str[0]=‘h’, str[1]=‘e’, …str[4]=‘o’*/
How to declare an array of strings ?
2D character array - char strs[20][5]; /* 20 strings with max-length=5 */
Example - Arrays in C :Example - Arrays in C #include
#include
/* Print 26 letters in lower case and upper case */
void main()
{
char a[2] = {'a', 'A'}; /* One dimensional array */
int b[2][26]; /* Two dimensional array */
int i;
for(i = 0; i < 26; i++)
{
b[0][i] = a[0] + i; /*Use the ASCII value of a[0] */
printf("%c ", b[0][i]); /*print the letter with ascii b[0][i] */
}
printf("\n");
for(i = 0; i < 26; i++)
{
b[1][i] = a[1] + i; /*Use the ASCII value of a[1] */
printf("%c ", b[1][i]); /*print the letter with ascii b[1][i] */
}
}
Pointers in C :Pointers in C Declare pointers to any data type using dereference operator *
int* int_ptr;
char* ch_ptr;
void* void_ptr;
A pointer takes its value as the address in memory of another variable int a = 5
int* a_ptr;
a_ptr = &a;
/* ‘&’ : address of operator */
(*a_ptr) ++ ;
/* ‘*’ : dereference operator */ a a_ptr
Pointer example :Pointer example
malloc, free – Allocate/Free Memory Blocks :malloc, free – Allocate/Free Memory Blocks Allocates memory blocks
Returns a void pointer to the allocated space
Return NULL if there is insufficient memory available
To return a pointer to a type other than void, use a type cast on the return value.
Example:
int* i_ptr = (int*) malloc (10 * sizeof(int) );
/* Allocate a memory block with size of 10 int variables. */
Deallocates or frees a memory block.
Example:
free( i_ptr ); /* ignore if i_ptr is null */ void *malloc( size_t size ); void free( void *memblock );
Example of pointers, malloc, free :Example of pointers, malloc, free #include
#include
void main()
{
int cost = 5, i;
int* cost_ptr;
cost_ptr = &cost; /*Let cost_ptr point to "cost“ */
printf("Pointer = %d. Dereference = %d\n", cost_ptr, *cost_ptr);
cost_ptr = (int*) malloc( 10 * sizeof(int));
for (i = 0; i < 10; i++)
{
cost_ptr [i] = i*2; /* cost_ptr can be used as an array variable*/
printf("value %d: %d\t", i, cost_ptr[i]);
/* You can also explicitly use the memory location of ith element (can be dangerous).*/
*(cost_ptr + sizeof(int) * i) = 2*i ;
printf("value %d: %d\n", i, *(cost_ptr + sizeof(int) * i));
}
/* Free the allocated mormory if you don't use it in the future */
free( cost_ptr);
}
Implement singly linked list in C :Implement singly linked list in C head Define structure with necessary data fields.
struct StrListElement
{
int value; /* value of current list element */
struct StrListElement* next; /* pointing to next element in the list */
};
...
StrListElement temp;
StrListElement* temp_ptr = &temp ;
User can explicitly access structure data fields use ‘.’ or ‘->’
“->” is used after a pointer to structure variable:
temp_ptr->value = 5; temp_ptr->next = null;
“.” is used after a structure variable:
temp.value = 5; temp.next = null;
Add elements to the singly linked list :Add elements to the singly linked list struct StrListElement* head = NULL; //Head of the singly linked list
struct StrListElement* str_elem_ptr;
int i;
for( i = 0; i value = i; /*
/* Add new element to the head of the list */
str_elem_ptr -> next = head;
head = str_elem_ptr;
} head same function as addFirst method
Other operations on singly linked list :Other operations on singly linked list Traverse elements in the list
str_elem_ptr = head;
while(str_elem_ptr != NULL)
{
printf("%d\n", str_elem_ptr->value);
str_elem_ptr = str_elem_ptr -> next;
}
Delete elements from the head of list. Free the memory of deleted elements
while(head != NULL)
{
str_elem_ptr = head;
head = str_elem_ptr -> next;
free(str_elem_ptr);
}
C functions :C functions A function has the following layout:
return-type function-name ( argument-list-if-necessary )
e.g.
int foo( int a, int b ) { ..}
void f2(int* pa) {..}
Arguments are always pass by values in C
i.e. “Local copies'' of the values of the arguments are passed to the functions
What if we want to pass values out of a function ?
Solution 1: return value (but at most 1 value can returned)
Solution 2: pointers
Pass arguments in/out of C functions :Pass arguments in/out of C functions What are the values of v1 and v2 after swap1 and swap2 ?
char v1=‘a’, v2 = ‘b’,
char* p1 = &v1;
char* p2 = &v2;
swap1 ( v1, v2 );
swap2 ( p1, p2 ); void swap1 (char v1, char v2)
{
char temp;
temp = v1;
v1 = v2;
v2 = temp;
} void swap2 (char* v1, char* v2)
{
char temp;
temp = *v1;
*v1 = *v2;
*v2 = temp;
} /* v1 = ‘a’, v2 = ‘b’. */
/* v1 = ‘b’, v2 = ‘a’. */