Post on 13-Dec-2015
CS 261 – Recitation 2
Fall 2013
Oregon State University
School of Electrical Engineering and Computer Science
CS 261 – Data Structures
Outline
• Programming in Co Compiling reviewo Preprocessoro Headerso Random numberso Pointerso Dynamic memory allocationo Structures
2
CS 261 – Data Structures
Compiling with GCC:
gcc <list of options> sourcefile.c
e.g.: gcc –Wall –std=c99 -o test test.c
Compiling with Makefile:default:main
main: main.cgcc –Wall –std=c99 main.c –o main
clean:rm main main.o
Executed when you type “make”
Executed when you type “make clean”
Compiling Review
3
The C Preprocessor
• C Preprocessor– preprocesses every source file before
performing the actual translation– replaces macros with their definitions
• “#define” directive: Used to define macros– Syntax:#define name [replacement_text]
– Example:#define BUF_SIZE 512#define MAX(a,b) ((a) > (b) ? (a) : (b))
CS 261 – Data Structures 4
The C Preprocessor (cont.)
• Consider the following code
CS 261 – Data Structures 5
struct myArray {
int data[100];
int count;
};
int myArrayTop(struct myArray *da);
int myArrayGet (struct myArray *v, int index);
struct myArray {
double data[100];
int count;
};
double myArrayTop(struct myArray *da);
double myArrayGet (struct myArray *v, int index);
The C Preprocessor (cont.)
• Solution in C
CS 261 – Data Structures 6
#define TYPE int
struct myArray {
TYPE data[100];
int count;
};
TYPE myArrayTop(struct myArray *da);
TYPE myArrayGet (struct myArray *v, int index);
#define TYPE double
struct myArray {
TYPE data[100];
int count;
};
TYPE myArrayTop(struct myArray *da);
TYPE myArrayGet (struct myArray *v, int index);
The C Preprocessor (cont.)
• Other directives• #if, #elif, #else, #endif• #ifdef and #ifndef
# ifndef TYPE# define TYPE double# endif
More about C Preprocessorhttp://en.wikipedia.org/wiki/C_preprocessor
CS 261 – Data Structures 7
# define TYPE int
Header files
CS 261 – Data Structures 8
• Purposes• To store standard library functions. E.g.
stdio.h• To store interfaces of C modules. E.g. dyArray.h
/* Prototypes */void dyArrayInit(struct dyArray *da, int
initialCapacity);void dyArrayFree (struct dyArray *v);
/* stack operations interface */void dyArrayPush(struct dyArray *da, TYPE e);void dyArrayPop(struct dyArray *da);TYPE dyArrayTop(struct dyArray *da);int dyArrayIsEmpty(struct dyArray *da);
Header files (cont.)
CS 261 – Data Structures 9
• To include a standard library in C, use “<>”.
E.g: #include <stdio.h>When using angle brackets, the
preprocessoronly searches for it in directories in yoursystem’s PATH variable.
• To include a header file, use quotation marks “”.
E.g: #include “sort.h”When using quotation marks, the
preprocessorfirst looks for the file in the current
workingdirectory.
CS 261 – Data Structures
Some useful headers are:
• stdlib.h: Contains the memory management tools like malloc(),calloc(), and free().
• stdio.h: Contains definitions for printf() and scanf(), useful functions for handling I/O.
• math.h: More advanced math functions, sqrt(), abs(), exp(), etc.
• ctype.h: Contains functions for working with characters
• time.h: Contains functions for accessing the system clock
Some particularly useful header files
10
CS 261 – Data Structures
Pseudo-random numbers in C
Some of the functionality that will be useful for your homework is the creation of random numbers using rand(), which is defined in stdlib.h as:
int rand ( void );
This function returns a number between 0 – RAND_MAX
11
CS 261 – Data Structures
Pseudo-random numbers in C
In order to generate numbers in a range, you can use the modulo (%) operator.
int value = rand(); ( value % 100 ) is in the range 0 to 99( value % 100 + 1 ) is in the range 1 to 100( value % 30 + 1985 ) is in the range 1985 to 2014
12
CS 261 – Data Structures
Pseudo-random numbers in C
Without a seed value, rand() will usually return the same sequence of random numbers.
In order to properly seed the pseudo-random number generator first call srand(time(NULL)).
Which header file do you think the time function is declared in?
13
CS 261 – Data Structures
Pseudo-random numbers in C
/* srand example */ #include <stdio.h> #include <stdlib.h> #include <time.h> int main () {
printf ("First number: %d\n", rand() % 100); srand ( time(NULL) ); printf ("Random number: %d\n", rand() % 100); srand ( 1 ); printf ("Again the first number: %d\n", rand()
%100);return 0;
}
14
CS 261 – Data Structures
Pseudo-random numbers in C
First number: 41 Random number: 13 Again the first number: 41 (seed is 1)
*If seed is set to 1, the generator is reinitialized to its initial value and produces the same values as before any call to rand or srand.
15
CS 261 – Data Structures
Pseudo-random numbers in C
In order to generate a list of unique numbers between two values there a couple of techniques
•Generate an ordered list then permute the elements
•Generate random numbers then simply check to see if the generated number is in use yet.
16
Pointers
• A pointer represents the address and type of a variable or a function.
CS 261 – Data Structures 17
a is a pointer whose value is the address of b a == &b and *a == b
Pointers
• Two fundamental operators:– &: address-of operator – to get a pointer to (address of) a
variable– *: dereference operator - get the thing the pointer points
to.
• * is also used to declare a pointer variableint i=5, int* p;p = &i;
• Note: – The name of an array is automatically converted to a
pointer to the array's first element.– The value of a null pointer is 0 or NULL.CS 261 – Data Structures 18
Pointers
CS 261 – Data Structures 19
var. name
value address
ptr ??? 0xA1
0xA3
var. name value address
a ??? 0x0A
b ??? 0x0C
int main { int *ptr; int a,b; a = 12; ptr = &a; b = *ptr;}
var. name value address
a 12 0x0A
b ??? 0x0C
var. name
value address
ptr 0x0A 0xA1
0xA3
var. name value address
a 12 0x0A
b 12 0x0C
Why pointers
•to simulate passing parameters by reference
•to pass a function big chunks memory
•to speed up the program
•to impress friends
CS 261 – Data Structures 20
Simulate passing parameter by reference
void swap(int x, int y) {
int temp; temp = x; x = y; y = temp;}
CS 261 – Data Structures 21
a = 12;b = 13;swap(a,b);
Is this code correct?
Call-by-value semantics
var. name
value
x ??
y ??
var. name
value
a 12
b 13
copied
main function’s code
var. name
value
x 12
y 13
copied
var. name
value
x 13
y 12
Simulate passing parameter by reference(cont.)
CS 261 – Data Structures 22
a = 12;b = 13;swap(&a,&b);
How about this code?
var. name
value
x ??
y ??
var. name
value
address
a 12 0x0A
b 13 0x0C
copied
main function’s code
copied
void swap(int *x, int *y) {
int temp; temp = *x; *x = *y; *y = temp;}
*x, *y are “aliases” of a and b
var. name
value
x 0x0A
y 0x0C
var. name
value
address
a 13 0x0A
b 12 0x0C
Pointer arithmetic
• Two arithmetic operations can be performed on pointers:– An integer can be added to or subtracted from a
pointer.– One pointer can be subtracted from another of
the same type.
• In arithmetic operations on pointers, the size of the objects pointed to is automatically taken into account. Which is great because you don’t have to multiply by sizeof(TYPE) all the time.
CS 261 – Data Structures 23
Pointer arithmetic (cont.)
An important thing to remember: *(ptr+num) == ptr[num]
int a[3] = { 0, 10, 20 }; /* An array with 3 elements */int *ptr_a = a; /* Let ptr_a point to a[0] */
/* pointers to the i-th element */&a[i] , a+i , ptr_a+i
/* the i-th array element */a[i] , *(a+i) , *(ptr_a+i) , ptr_a[i]
/* Let pa point to a[2] */ptr_a = a+2; or ptr_a = ptr_a + 2; int n = ptr_a – a; /* what is the value of n? */
CS 261 – Data Structures 24
Dynamic Memory Allocation
• Consider this code:
struct dyArray { /* dynamic array structure */
TYPE data[100]; int size; int capacity;};
What’ s wrong with this code?
CS 261 – Data Structures 25
Dynamic Memory Allocation (cont.)
• Corrected version:
struct dyArray { /* dynamic array structure */
TYPE *data; int size; int capacity;};
The memory needed to store data will be dynamically allocated.
CS 261 – Data Structures 26
Dynamic Memory Allocation (cont.)
struct dyArray { /* dynamic array structure */ TYPE *data; int size; int capacity;};
struct dyArray da;da.capacity = 100; da.size = 0;da.data = (TYPE *) malloc(da.capacity*sizeof(TYPE));assert(da.data != NULL);…free(da.data);
CS 261 – Data Structures 27
Structures in C
• The `struct` type:– A bit similar to class in Java with no methods.
• Declare a struct data type:struct item {/* item = name of this struct */char name[40];char color[20];double price; };
CS 261 – Data Structures 28
Structures in C (cont.)
• Declare variables with the structure type:struct item a1, a2;struct item *pointer_to_a1;struct item myItems[100];
• Initialize structure variables:struct item flower=
{ ”rose", ”green”, 2.49 };struct item bouquet[10] ;bouquet[0] = flower;
CS 261 – Data Structures 29
Structures in C (cont.)
• Access structure members:
– Using the dot operatorflower.name /* The array 'name' */flower.price /* The double variable 'price’
*/
– Using pointers to structsstruct item *pArticle;pArticle = &flower; /*Let pArticle point to flower*/
pArticle->color=”red”;/* Access members of flower */
pArticle->price=5.0; /* using the pointer pArticle*/
CS 261 – Data Structures 30