ISP – 6 th Recitation What’s void? Pointer to pointer/Array of pointers/Two dimensional array “Random” numbers Semaphores Code examples.

Slides:



Advertisements
Similar presentations
The debugger Some programs may compile correctly, yet not produce the desirable results. These programs are valid and correct C programs, yet not the programs.
Advertisements

C Structures What is a structure? A structure is a collection of related variables. It may contain variables of many different data types---in contrast.
Dynamic memory allocation
An introduction to pointers in c
Programming and Data Structure
Unions The storage referenced by a union variable can hold data of different types subject to the restriction that at any one time, the storage holds data.
Lecture 20 Arrays and Strings
CS1061: C Programming Lecture 21: Dynamic Memory Allocation and Variations on struct A. O’Riordan, 2004, 2007 updated.
Spring 2005, Gülcihan Özdemir Dağ Lecture 12, Page 1 BIL104E: Introduction to Scientific and Engineering Computing, Spring Lecture 12 Outline 12.1Introduction.
Managing Memory Static and Dynamic Memory Type Casts Allocating Arrays of Dynamic Size Resizing Block of Memory Returning Memory from a Function Avoiding.
Managing Memory DCT 1063 PROGRAMMING 2 Mohd Nazri Bin Ibrahim Faculty of Computer, Media & Technology TATi University College
Kernighan/Ritchie: Kelley/Pohl:
Memory Allocation. Memory A memory or store is required in a computer to store programs (or information or data). Data used by the variables in a program.
Dynamic Memory Allocation in C++. Memory Segments in C++ Memory is divided in certain segments – Code Segment Stores application code – Data Segment Holds.
1 Homework Turn in HW2 at start of next class. Starting Chapter 2 K&R. Read ahead. HW3 is on line. –Due: class 9, but a lot to do! –You may want to get.
ISP – 3 rd Recitation “The joy of Windows API” Processes Threads Handles Relevant functions A simple code example.
ISP – 7 th Recitation Mid semester!!! Semaphores – reminder Events Code examples.
ISP – 5 th Recitation Mutexes Code example. Mutex Wikipedia definition: Mutual exclusion (often abbreviated to mutex) algorithms are used in concurrent.
Pointers. Topics Pointers Pointer Arithmetic Pointers and Arrays.
1 Chapter 9 Arrays and Pointers. 2  One-dimensional arrays  The Relationship between Arrays and Pointers  Pointer Arithmetic and Element Size  Passing.
Unix Process Environment. main Function A C program starts execution with a function called main. The prototype for the main function is: int main (int.
ARRAYS AND POINTERS Although pointer types are not integer types, some integer arithmetic operators can be applied to pointers. The affect of this arithmetic.
ISP – 4 th Recitation Times System Errors Threads Waits Code examples.
1 Random numbers Random  completely unpredictable. No way to determine in advance what value will be chosen from a set of equally probable elements. Impossible.
Pointers Applications
Arrays and Pointers in C Alan L. Cox
‘C’ LANGUAGE PRESENTATION.  C language was introduced by Dennis Ritchie..  It is a programming language, which can make a interaction between user and.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Tevfik Bultan Lecture 12: Pointers continued, C strings.
1 C - Memory Simple Types Arrays Pointers Pointer to Pointer Multi-dimensional Arrays Dynamic Memory Allocation.
The basics of the array data structure. Storing information Computer programs (and humans) cannot operate without information. Example: The array data.
Week 7 - Wednesday.  What did we talk about last time?  scanf()  Memory allocation  malloc()  free()
ECE 103 Engineering Programming Chapter 47 Dynamic Memory Alocation Herbert G. Mayer, PSU CS Status 6/4/2014 Initial content copied verbatim from ECE 103.
Dynamic memory allocation and Pointers Lecture 4.
 2008 Pearson Education, Inc. All rights reserved Case Study: Random Number Generation C++ Standard Library function rand – Introduces the element.
Pointers: Basics. 2 What is a pointer? First of all, it is a variable, just like other variables you studied  So it has type, storage etc. Difference:
Pointers in C Computer Organization I 1 August 2009 © McQuain, Feng & Ribbens Memory and Addresses Memory is just a sequence of byte-sized.
5-1 Embedded Systems C Programming Language Review and Dissection III Lecture 5.
Pointers *, &, array similarities, functions, sizeof.
C Programming Lecture 16 Pointers. Pointers b A pointer is simply a variable that, like other variables, provides a name for a location (address) in memory.
12/23/2015Engineering Problem Solving with C++, second edition, J. Ingber 1 Engineering Problem Solving with C++, Etter/Ingber Chapter 9 An Introduction.
Copyright ©: Nahrstedt, Angrave, Abdelzaher1 C Basics Tarek Abdelzaher and Vikram Adve.
Variables and memory addresses
+ Arrays & Random number generator. + Introduction In addition to arrays and structures, C supports creation and manipulation of the following data structures:
1D Arrays and Random Numbers Artem A. Lenskiy, PhD May 26, 2014.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
ONE DIMENSIONAL ARRAYS AND RANDOM NUMBERS. Introduction In addition to arrays and structures, C supports creation and manipulation of the following data.
Advanced Pointer Topics. Pointers to Pointers u A pointer variable is a variable that takes some memory address as its value. Therefore, you can have.
Function Call Stack and Activation Frame Stack Just like a pile of dishes Support Two operations push() pop() LIFO (Last-In, First-Out) data structure.
1 Dynamic Memory Allocation. 2 In everything we have done so far, our variables have been declared at compile time. In these slides, we will see how to.
ENEE150 – 0102 ANDREW GOFFIN Dynamic Memory. Dynamic vs Static Allocation Dynamic  On the heap  Amount of memory chosen at runtime  Can change allocated.
Announcements Assignment 2 Out Today Quiz today - so I need to shut up at 4:25 1.
C Tutorial - Pointers CS 537 – Introduction to Operating Systems.
Chapter INTRODUCTION Data Types and Arithmetic Calculations.
BIL 104E Introduction to Scientific and Engineering Computing Lecture 9.
Pointers: Basics. 2 Address vs. Value Each memory cell has an address associated with it
Windows Programming Lecture 03. Pointers and Arrays.
DYNAMIC MEMORY ALLOCATION. Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements.
L131 Assignment Operators Topics Increment and Decrement Operators Assignment Operators Debugging Tips rand( ) math library functions Reading Sections.
Case Study: Pthread Synchronization Dr. Yingwu Zhu.
Stack and Heap Memory Stack resident variables include:
UNIT 5 C Pointers.
Pointers.
Arrays, For loop While loop Do while loop
Assignment Operators Topics Increment and Decrement Operators
Pointers The C programming language gives us the ability to directly manipulate the contents of memory addresses via pointers. Unfortunately, this power.
Assignment Operators Topics Increment and Decrement Operators
EENG212 – Algorithms & Data Structures Fall 07/08 – Lecture Notes # 5b
C Programming Lecture-8 Pointers and Memory Management
26.
Assignment Operators Topics Increment and Decrement Operators
Presentation transcript:

ISP – 6 th Recitation What’s void? Pointer to pointer/Array of pointers/Two dimensional array “Random” numbers Semaphores Code examples

What’s void? In C, void is a data type with two uses: 1.When used directly as a return value of functions, it means that the function doesn’t return a value (procedure in other programming languages). void myFunction(int a) { printf(“a+1=%d\n”,a); } //no return and no compilation warning

What’s void? 2. When used as a pointer to void (void *p_void) it indicates a pointer to an unspecified data type. int num; void *p_void; char *p_char; p_char=# //generates a warning p_void=# //no warning generated

Pointers Important notes to understand about pointers: A pointer is an address to a place in memory. Memory addresses have the same size (4 bytes/ 32bits / int). sizeof(float *) = sizeof(int *) = sizeof(char *) = sizeof(void *) We define specific pointers (float *p_float) to allow the compiler to “understand” correctly the data in the address of the pointer and warn us of inconsistencies in code.

Examples float r_num; int i_num, *p_int; llist *head; p_int=&r_num; //issues a warning p_int=&i_num; //works alright r_num=*p_int; //another warning head->next = NULL; //works ok p_int=head; //warning p_int->next = NULL; //ERROR!

Array of Pointers Recall that in C, an array is defined as a pointer to the head of the array. An array of pointers is thus a pointer to a pointer. Examples: char **data, *str; Both data and str are pointers and have a value of a memory address. str[n] is a char variable and not a pointer. data[n] is a pointer to an array of type char. Note that data[n] is equivalent, in type, to str.

Array of Pointers data=malloc(5*sizeof(char *)); data data[3]=malloc(2*sizeof(char)); 0x1ff 0x200 0x201 0x202 0x203 0x204 0x205 0x206 0x207 Addr 0x206 Suppose you now wanted to increase the number of pointers in the array of pointers to 10. How can you do it and what would happen to the memory? Hint: check realloc() out.

Two Dimensional Arrays Since an array is seen as a pointer in C, it’s possible to look at a pointer to a pointer as a two dimensional array. int **data,tmp; data = (int **) malloc(5*sizeof(int *)); for (tmp=0;tmp<5;tmp++) data[tmp] = (int *) malloc (10*sizeof(int)); data[0][3]=15;

Random Numbers Computers are state machines. Their behavior has to be predictable and has to repeat itself given similar conditions. As such, computers can’t generate truly random numbers. They can, however, generate pseudo random numbers. Pseudo random numbers are sequences of numbers that the computer computes according to a certain algorithm based on a given number called “seed”. For a given seed, the computer would always generate the same sequence of pseudo random numbers.

srand() Initializes the random number generator with a given seed. Syntax: void srand (unsigned int seed); seed is naturally the seed number. We often use the current time as a seed: srand(time(NULL)); srand() and rand() require stdlib.h and time() requires time.h.

rand() Generates a random number. Syntax: int rand (void); The returned number is a pseudo random number in the range of 0 to RAND_MAX (normally but defined in cstdlib.h). If we desire a random number in the range of 0:N- 1, we can use: value = rand() % N;

Semaphores A semaphore object is a synchronization object that maintains a count between zero and a specified maximum value. The count is decremented each time a thread completes a wait for the semaphore object and incremented each time a thread releases the semaphore. When the count reaches zero, no more threads can successfully wait for the semaphore object state to become signaled. The state of a semaphore is set to signaled when its count is greater than zero, and nonsignaled when its count is zero.

Creating a Semaphore Creating a new semaphore Syntax : HANDLE CreateSemaphore( SECURITY_ATTRIBUTES *SemaphoreAttributes, LONG InitialCount, Long MaximumCount, char* Name ); InitialCounts is the initial number contained in the semaphore. MaximumCount is the max number that the semaphore counts. Name field identifies the semaphore in the system/process. If name already exists, a handle to the sempahore is returned and GetLastError() shows ERROR_ALREADY_EXISTS.

Opening an Existing Semaphore Opening a semaphore Syntax : HANDLE OpenSemaphore( DWORD DesiredAccess, BOOL InheritHandle, char* Name ); DesiredAccess requires a minimum permission of SYNCHRONIZE.

WaitForSingleObject() - Semaphore WaitForSingleObject() is used for waiting for an object to become “signaled”. Syntax : DWORD WaitForSingleObject( HANDLE hObject, DWORD dwMilliseconds ); For semaphores, “Signaled” means that the semaphore’s counter value is bigger than 0. Non signaled means that the counter’s value is 0.

ReleaseSemaphore() Release increases the count of the specified semaphore object. Syntax : BOOL ReleaseSemaphore( HANDLE hSemaphore, LONG ReleaseCount, LONG *PreviousCount); ReleaseCount – a number by which to increase the counter PreviousCount – a pointer to a long int where the previous count can be stored. Can be NULL if not necessary. Returns 0 if failed, nonzero if successful Note: Make sure you only release the semaphore with the right number in ReleaseCount.