代写代考 COSC 407: Introduction to Parallel Computing

Intro to Parallel Computing
Topic 2 – 2: Intro to C – Part 2
COSC 407: Introduction to Parallel Computing
Topic 2 – 2: Introduction to C – Part 2 COSC 407: Into to Parallel Computing

Copyright By PowCoder代写 加微信 powcoder

§ Previously:
– Intro to C, Java vs C, Data types, variables, Operators – I/O
– Arrays, Functions, Pointers
– Pointers (memory allocation, 2D arrays, functions) – Error Handling
– String processing
– struct, typedef
– Preprocessors, Compiling C programs
Topic 2 – 2: Introduction to C – Part 2 COSC 407: Into to Parallel Computing

Pointers (Review)
What is a pointer?
– A pointer is a variable that holds a memory address
• Apointerisdeclaredusing*
type *identifier
* can appears anywhere between identifier and type
§ Example1: int y = 5;
int *py, *px; py = &y;
// integer variable initialized to 5 // pointers to an integer
// p has the memory address of y
How to access a value at an address available in a pointer?
– use the * operator which means “value at”
intx=*py; //x=thevaluestoredattheaddressinp px px = &x; // px points to x now
*px++; // now x is 6
Topic 2 – 2: Introduction to C – Part 2 COSC 407: Into to Parallel Computing
Pointers, cont’d
§ Remember these two operators:
– Value at address (*):
• gives the value stored at a particular address
• *p is y in the example in the previous slide – This is called “dereferencing” p
– Address of (&):
• gives address of a variable
– Also called ‘indirection operator’
Topic 2 – 2: Introduction to C – Part 2 COSC 407: Into to Parallel Computing

Heap vs Stack
§ In C, there are three different pools of memory available
– static:globalvariablestorage
– stack:localvariablestorage(automatic,continuousmemory)
• A stack frame is created when you call a function
• Used when you declare a variable inside a function
• When you leave the function, the stack frame is ‘popped off’ the stack
– Variablesdisappear(youdon’thavetoworryaboutcleaningup – heap:dynamicstorage(largepoolofmemory,notallocatedin
contiguous order).
• heap:dynamicstorage(largepoolofmemory,not allocated in contiguous order).
– Managedbytheprogrammer,theabilitytomodifyitis somewhat boundless
– Variablesareallocatedandfreedusingfunctionslikemalloc() and free()
– Heapislarge,andisusuallylimitedbythephysicalmemory available
– Requirespointerstoaccessit
A nice example: https://craftofcoding.wordpress.com/2015/12/07/memory-in-c-the-stack-the-heap-and-static/
Topic 2 – 2: Introduction to C – Part 2 COSC 407: Into to Parallel Computing
malloc() and free()
§ The C function malloc allocates memory space given in bytes.
– calloc allocates a number of bytes and initializes them to zero
– mallocreturnsapointertotheallocatedmemory,orNULL if the memory cannot be allocated.
§ The C function free releases the allocated space
int* buffer = malloc(10 * sizeof(int));
for (i = 0; i < 10; i++) buffer[i] = i; for (i = 0; i < 10; i++) printf("buffer[%d] is %d\n", i, buffer[i]); free(buffer); Free the memory Topic 2 - 2: Introduction to C – Part 2 COSC 407: Into to Parallel Computing allocates 10 integers in the memory Using an offset with a pointer Difference Between [ ] and * to Declare Arrays § This statement creates the array on the stack int arr[3]; – Once we exit the function where the array is created, the array is removed from the stack (as well as other local variables). § This statements creates the array on the heap int* arr = malloc(3*sizeof(int)); – The memory reserved on the heap is not released until we call free() § When to use which? – Stack: for small arrays that you only need locally in a function. – Heap: for large arrays that you want to keep around for a longer time (e.g. like a global). Heap allocated arrays can also be dynamically resized using realloc() function. Topic 2 - 2: Introduction to C – Part 2 COSC 407: Into to Parallel Computing Using Pointers with an Offset § As you have seen in previous example, an offset can be used with a pointer using array notation to access a value in the memory § Example: int y = 10; int* p = &y;// p = y address printf("%d\n", p + 1); printf("%d\n", &p[1]); printf("%d\n", &y + 1); printf("%d\n", p[1]); printf("%d\n", *(p+1)); Topic 2 - 2: Introduction to C – Part 2 print (y address + 4 bytes) COSC 407: Into to Parallel Computing print value at (y address + 4 bytes) Pointers and 2D Arrays § Let’s say we have two 2D arrays that we want to process in loops (e.g. initialize to 0’s) int A[10][10]; int* B = malloc(100 * sizeof(int)); for (int r = 0; r < 10; r++){ for (int c = 0; c < 10; c++) { A[r][c] = 0; // this is ok B[r][c] = 0; // ERROR! //10x10 array //10x10 array You cannot use [r][c] with dynamically allocated arrays (B can only be a pointer or a vector). Solution: use row-major format! Topic 2 - 2: Introduction to C – Part 2 COSC 407: Into to Parallel Computing Memory Layout of a Matrix in C M0,0 M1,0 M2,0 M3,0 M0,1 M1,1 M2,1 M3,1 M0,2 M1,2 M2,2 M3,2 M0,3 M1,3 M2,3 M3,3 2D arrays in C are stored like this in the memory M0,0 M1,0 M2,0 M3,0 M0,1 M1,1 M2,1 M3,1 M0,2 M1,2 M2,2 M3,2 M0,3 M1,3 M2,3 M3,3 © /NVIDIA and Wen-mei W. Hwu, 2007-2010, ECE 408, University of Illinois, Urbana-Champaign Topic 2 - 2: Introduction to C – Part 2 COSC 407: Into to Parallel Computing M0,0 M0,1 M0,2 M0,3 M1,0 M1,1 M1,2 M1,3 M2,0 M2,1 M2,2 M2,3 M3,0 M3,1 M3,2 M3,3 Row-Major Layout in C/C++ M0,0 M0,1 M0,2 M0,3 M1,0 M1,1 M1,2 M1,3 M2,0 M2,1 M2,2 M2,3 M3,0 M3,1 M3,2 M3,3 M M0 M1 M2 M3 M4 M5 M6 M7 M8 M9 M10 M11 M12 M13 M14 M15 Row*Width+Col = 2*4+1 = 9 à M9 M[r][c] = M[r * Width + c] © /NVIDIA and Wen-mei W. Hwu, 2007-2010, ECE 408, University of Illinois, Urbana-Champaign Topic 2 - 2: Introduction to C – Part 2 COSC 407: Into to Parallel Computing Question... § How do we access M2,3 if M was created using malloc? M0,0 M0,1 M0,2 M0,3 M1,0 M1,1 M1,2 M1,3 M2,0 M2,1 M2,2 M2,3 M3,0 M3,1 M3,2 M3,3 A. M[2][3] E. None of the above Topic 2 - 2: Introduction to C – Part 2 COSC 407: Into to Parallel Computing Using Pointers with Functions § When passing an address as an argument and store it in a pointer parameter, the function will have direct access to the passed variable. This is called "passing by reference” – Actuallypassingacopyoftheaddress void incrementBy1(int*); int main() { int x = 10; printf("x before: %d\n", x); incrementBy1(&x); printf("x after: %d\n", x); return 0; void incrementBy1(int* xp) { pass the address of x *xp = *xp + 1;// changes directly applied to x } Topic 2 - 2: Introduction to C – Part 2 COSC 407: Into to Parallel Computing Pointers to Functions § In C, the name of a function is a pointer to that function. § For example, foo is a pointer to its function. § In C, we can create additional function pointers, – i.e.variablesthatpointtofunctions. – Functionpointerscanbeusedtoaccessthefunctionsthey point to. Topic 2 - 2: Introduction to C – Part 2 COSC 407: Into to Parallel Computing int foo(){ int foo(){ Pointers to Functions Declaration: int (*f)(); – Here,fisdeclaredasapointertoafunctionthatreturns int type - the return type must be specified (e.g. int, double, etc), but the argument can be left out. • i.e.functionpointedtobyfcouldreceiveany arguments or no arguments. – Note:theparenthesesaround*fareessentialinthe declarations. • Without them, i.e. int *f(), then we are declaring a function f that returns an int pointer: i.e. int* f(); Topic 2 - 2: Introduction to C – Part 2 COSC 407: Into to Parallel Computing Pointers to Functions, cont’d Assume we have a function pointer declared as follows: int (*f)(); and assume we have two functions: int sum(int a, int b){...} int mult(int a, int b){...} We can now assign fp to any of the above two functions : f = sum; printf("3+4=%d", f(3,5)); //output:8 printf("3+4=%d", sum(3,5));//output:8 f = mult; //now fp points to mult() printf("3*4=%d", f(3,5)); //output:15 This feature becomes handy when you want to pass a function to another. Topic 2 - 2: Introduction to C – Part 2 COSC 407: Into to Parallel Computing Passing a Function to Another int sum(int a, int b) {return a + b;} int mult(int a, int b){return a * b;} int process(int a, int b, int(*f)()){ return f(a, b); int main() { int r1 = process(3, 5, sum); printf("3 + 5 = %d\n", r1);//out:8 int r2 = process(3, 5, mult); printf("3 x 5 = %d\n", r2);//out:15 § In this example, process is a generic function that receives two integers and a process function – Whenwepasssum,the two integers are added – Whenwepassmult,they are multiplied Topic 2 - 2: Introduction to C – Part 2 COSC 407: Into to Parallel Computing Passing a Function to Another § In this example, process is a generic function that receives two integers and a process function – Whenwepasssum,the two integers are added – Whenwepassmult,they are multiplied Topic 2 - 2: Introduction to C – Part 2 COSC 407: Into to Parallel Computing int sum(int a, int b) {return a + b;} int mult(int a, int b){return a * b;} int process(int a, int b, int f() ){ return f(a, b); int main() { int r1 = process(3, 5, sum); printf("3 + 5 = %d\n", r1);//out:8 int r2 = process(3, 5, mult); printf("3 x 5 = %d\n", r2);//out:15 Simpler syntax Aside: Pointer to a Pointer int *px, **ppx; px = &x; // take the address of x ppx = &px; // take the address of px printf("Value available at *px = %d\n", *px );//prints 7 printf("Value available at **ppx = %d\n", **ppx);//prints 7 *ppx **ppx *px § ppx contains the address of px, which points to the location of x. – *px = x’s value – **ppx = x’s value – *ppx = the address in px • *ppxispx – so sayingpx = &x is the same as*ppx = &x Topic 2 - 2: Introduction to C – Part 2 COSC 407: Into to Parallel Computing Aside: Pointer to a Pointer § Useful when passing a pointer by-reference to a function – And the function is expected to modify the pointer’s value. – The example demonstrate a function that stores the address of a new allocated memory within a pointer argument s2 so that s2 points to the new memory space. Topic 2 - 2: Introduction to C – Part 2 COSC 407: Into to Parallel Computing int allocstr(int, char**); int main(void) { char* s1 = "Hello, world!"; char* s2 = NULL; if ( allocstr(strlen(s1), &s2) ) strcpy(s2, s1); fprintf(stderr, "out of memory\n"); return 0; // s1 points to a string // s2 points to nothing (s2=0) Hello, World! // funct to allocate memory for a string and retruns 1, otherwise returns 0 int allocstr(int len, char** p2) { //p2 = address of s2 (*p2 is s2) char* p1 = malloc(len + 1); // allocate space in memory if (p1 == NULL) return 0; // if cannot allocate space *p2 = p1; // s2 points at same memory space pointed at by p1 return 1;} Aside: void* pointers § Void pointers can be assigned any data type. You can cast intx=10; doubley=10; void pointers to other types. double *p2, *p3; p1 = (int*)vp; p3 = (double*)vp; // p1 should point to int // p2 and p3 should point to // pv can point to any type // pv can point to int // no need to cast (p1 is int*) // explicit casting is not needed // pv can also point to double // no need to cast // casting not needed printf("x: %d\n", *p1); printf("y: %f\n", *p2); printf("y: %f\n", *p3); Topic 2 - 2: Introduction to C – Part 2 // print value of x // print value of y // print value of y COSC 407: Into to Parallel Computing Aside: void* pointers § We cannot dereference a void pointer – Cast before we dereference a void pointer int x = 10; int *p1; void *vp; // p1 should point to int // pv can point to any type // pv can point to int //*vp = 10; *(int*)vp = 10; //we must cast before dereferencing vp //error! CANNOT dereference void pointers p1 = vp; //ok to have int* p1 = vp then dereference p1 printf("x: %d\n", *p1); printf("x: %d\n", *(int*)vp); Topic 2 - 2: Introduction to C – Part 2 // p1 is int*, no need to cast // again, void* needs casting COSC 407: Into to Parallel Computing Aside: Functions that Return a Void Pointer § The code below should print the address of x twice void* foo(int* ptr){ return ptr; } int main() { int x = 10; int* p = &x; printf("p: %p\n", p); p = foo(p); // p is int*, foo returns *void printf("p: %p\n", p); return 0; } Topic 2 - 2: Introduction to C – Part 2 COSC 407: Into to Parallel Computing Error Handling #include /* for fprintf and stderr */ #include /* for exit and EXIT_FAILURE */ int main(void) {
int dividend = 50; int divisor = 0; int quotient;
if (divisor == 0) {
fprintf(stderr, “Division by zero! Aborting…\n”);
exit(EXIT_FAILURE); /* indicate failure.*/ }
quotient = dividend / divisor;
exit(EXIT_SUCCESS); /* indicate success.*/ }
Topic 2 – 2: Introduction to C – Part 2 COSC 407: Into to Parallel Computing

§ A string in C is a 1-D array of characters terminated by the null character ‘\0’
char name[] = “UBC Okanagan”;
index 0 1 2 3 4 5 6 7 8 9 10 11 12 data U B C O k a n a g a n \0
§ Useful string functions (s1, s2 are strings, ch is a character) – strlen(s1);
• Returns the length of s1 as integer – strcat(s1, s2);
• Concatenates s2 to the end of s1. – strcmp(s1, s2);
• Returns 0 if s1 and s2 are the same; -ve if s1s2 – strcpy(s1, s2);
• Copies s2 into s1. – strchr(s1, ch);
• Returns a pointer to the first occurrence of ch in s1 – strstr(s1, s2);
• Returns a pointer to the first occurrence of s2 in s1
Topic 2 – 2: Introduction to C – Part 2 COSC 407: Into to Parallel Computing
Strings, cont’d
§ Declaring a string with a variable length
int len = 10; //10 characters
char* temp = malloc(len+1); //10 chars + null terminator
§ There is no substring function. The following code can be used – Don’tforgettodeclareyourfunctionbeforemain.
Topic 2 – 2: Introduction to C – Part 2 COSC 407: Into to Parallel Computing

§ C has a complex data type called “struct” that groups a list of
variables to be placed under one name in the memory
– Unlikearrays,whichholdseveraldataitemsofthesame type, the items in C structs may be of different types
– A”struct”CANNOTcontainanyfunctions Syntax: Example:
Topic 2 – 2: Introduction to C – Part 2 COSC 407: Into to Parallel Computing
§ typedef is used to give a type a new name
– Synonyms for a datatype § Example
typedef unsigned char BYTE;
– After this statement, you can use BYTE to declare any variables of the type ‘unsigned char’
Topic 2 – 2: Introduction to C – Part 2 COSC 407: Into to Parallel Computing

typedef with struct § typedef may be used to give a name to a struct
– Instead of declaring using “struct point p”, use only “point p”
Adapted from: https://en.wikipedia.org/wiki/Struct_%28C_programming_language%29
Topic 2 – 2: Introduction to C – Part 2 COSC 407: Into to Parallel Computing
Standard Library stdlib.h
§ Useful values: – NULL
• the value of a null pointer constant. – EXIT_FAILURE
• return value for the exit function in case of failure. – EXIT_SUCCESS
• return value for the exit function in case of success. § Useful functions
– Conversion from string to numbers:
• atol or strtol
• atof or strtod
àreturns int
à returns long int à returns double
– void exit(int status)
• terminate the program normally.
– int rand(void)
• Returns a pseudo-random number in the range from 0 to maximum
possible integer.
Topic 2 – 2: Introduction to C – Part 2 COSC 407: Into to Parallel Computing

Preprocessors
§ #include : header files – #include
• During compilation, this statement is replaced with the text of stdio.h file
§ #define : Macro Expansions (constants and function-like macros)
– #define PI 3.14159 /* global constant */
– #define UBC “The University of British Colombia”
– #define SQUARE(x) ( (x) * (x) ) /* function-like macro */
– #define MAX(x,y) ( (x)>(y)? (x) : (y) )
§ #ifdef : Conditional Compilation #ifdef MACRONAME
// Do something if MACRONAME is defined
// Do something if MACRONAME is not defined
Topic 2 – 2: Introduction to C – Part 2 COSC 407: Into to Parallel Computing
Preprocessors, cont’d
#include
//#define DEBUG
#ifdef DEBUG
#define mydebug(s) printf(“%s\n”, s);
#define mydebug(s) printf(“undefined!”);
int main(){ mydebug(“abc”);
return 0; }
Topic 2 – 2: Introduction to C – Part 2
Prints “undefined”
COSC 407: Into to Parallel Computing
Uncomment to print “abc” (the argument)

Source code
Object code
(temp.c) (foo.o)
Compiling C Programs
Preprocessor
produces C code that has no preprocessing statements.
• Removecomments(/* */,//)
• Include header files (#include)
• Expand macros (#define)
• Join continued lines ( \ )
Compiler and Assembler produce object file (machine code for your statements, but not for functions from the header files)
• Think of object files as partially complete program with missing blocks of code (i.e. the code for functions from the header files).
Linker replaces the missing parts in the object files with the appropriate machine code.
(e.g., stdio.h)
Topic 2 – 2: Introduction to C – Part 2 COSC 407: Into to Parallel Computing
Keep in mind
§ Always initialize (especially pointers to NULL)
– Do not use pointers non-initialized or pointer to a
memory that was released
§ Don’t return a function local variables by reference § Check for errors
– no exceptions
§ An array is a pointer
Topic 2 – 2: Introduction to C – Part 2 COSC 407: Into to Parallel Computing

§ Next Lecture:
– Basics of Parallel Computing
• Concepts and Terminology – Introduction to POSIX threads
Topic 2 – 2: Introduction to C – Part 2
COSC 407: Into to Parallel Computing
§ Read An introduction to C Programming for Java Programmer, Handley. (AGAIN)
– AvailableonConnect.
§ Find a C reference for later use (library, online) – e.g.,http://www.tutorialspoint.com
§ Practice on C!!!
– RewriteallexerciseswehadinthenotesONYOUROWN – Findsomeonlinequizzesandpractice
Topic 2 – 2: Introduction to C – Part 2 COSC 407: Into to Parallel Computing

程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com