Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS 261 – Recitation 2 Fall 2013 Oregon State University School of Electrical Engineering and Computer Science.

Similar presentations


Presentation on theme: "CS 261 – Recitation 2 Fall 2013 Oregon State University School of Electrical Engineering and Computer Science."— Presentation transcript:

1 CS 261 – Recitation 2 Fall 2013 Oregon State University School of Electrical Engineering and Computer Science

2 CS 261 – Data Structures Outline Programming in C o Compiling review o Preprocessor o Headers o Random numbers o Pointers o Dynamic memory allocation o Structures 2

3 CS 261 – Data Structures Compiling with GCC: gcc sourcefile.c e.g.:gcc –Wall –std=c99 -o test test.c Compiling with Makefile: default:main main: main.c gcc –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

4 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 Structures4

5 The C Preprocessor (cont.) Consider the following code CS 261 – Data Structures5 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);

6 The C Preprocessor (cont.) Solution in C CS 261 – Data Structures6 #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);

7 The C Preprocessor (cont.) Other directives #if, #elif, #else, #endif #ifdef and #ifndef # ifndef TYPE # define TYPE double # endif More about C Preprocessor http://en.wikipedia.org/wiki/C_preprocessor CS 261 – Data Structures7 # define TYPE int

8 Header files CS 261 – Data Structures8 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);

9 Header files (cont.) CS 261 – Data Structures9 To include a standard library in C, use “<>”. E.g: #include When using angle brackets, the preprocessor only searches for it in directories in your system’s PATH variable. To include a header file, use quotation marks “”. E.g: #include “sort.h” When using quotation marks, the preprocessor first looks for the file in the current working directory.

10 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

11 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

12 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

13 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

14 CS 261 – Data Structures Pseudo-random numbers in C /* srand example */ #include 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

15 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

16 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

17 Pointers A pointer represents the address and type of a variable or a function. CS 261 – Data Structures17 a is a pointer whose value is the address of b a == &b and *a == b

18 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 variable int 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 Structures18

19 Pointers CS 261 – Data Structures19 var. namevalueaddress ptr???0xA1 0xA3 var. namevalueaddress a???0x0A b???0x0C int main { int *ptr; int a,b; a = 12; ptr = &a; b = *ptr; } var. namevalueaddress a120x0A b???0x0C var. namevalueaddress ptr0x0A0xA1 0xA3 var. namevalueaddress a120x0A b120x0C

20 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 Structures20

21 Simulate passing parameter by reference void swap(int x, int y) { int temp; temp = x; x = y; y = temp; } CS 261 – Data Structures21 a = 12; b = 13; swap(a,b); Is this code correct? Call-by-value semantics var. namevalue x?? y var. namevalue a12 b13 copied main function’s code var. namevalue x12 y13 copied var. namevalue x13 y12

22 Simulate passing parameter by reference(cont.) CS 261 – Data Structures22 a = 12; b = 13; swap(&a,&b); How about this code? var. namevalue x?? y var. namevalueaddress a120x0A b130x0C 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. namevalue x0x0A y0x0C var. namevalueaddress a130x0A b120x0C

23 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 Structures23

24 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 Structures24

25 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 Structures25

26 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 Structures26

27 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 Structures27

28 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 Structures28

29 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 Structures29

30 Structures in C (cont.) Access structure members: –Using the dot operator flower.name /* The array 'name' */ flower.price /* The double variable 'price’ */ –Using pointers to structs struct 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 Structures30

31 CS 261 – Data Structures31 That’s all for today!


Download ppt "CS 261 – Recitation 2 Fall 2013 Oregon State University School of Electrical Engineering and Computer Science."

Similar presentations


Ads by Google