1. Lab exercise C programming language

Parallel and disributed systems and algorithms 2015/16 1. Lab exercise C programming language Davor Sluga "The more I C, the less I see." Introduc...
2 downloads 0 Views 431KB Size
Parallel and disributed systems and algorithms 2015/16

1. Lab exercise C programming language Davor Sluga

"The more I C, the less I see."

Introduction • Lab exercises are mandatory and are being graded

• To complete Lab exercises successfully at least 70% of assignments have to be completed • Every week new assignment

• You can present your solution no later than 2 weeks after it was introduced • Grading: quantity, quality, speed

• Final project

2

Content • C/C++ programming language

• Programming with threads • pthreads • OpenMP

• Intel MIC architecture (Xeon Phi) • GPUs (OpenCL) • MPI library – national GRID

3

C programming language review • Pointers and arrays

• Function pointers • Dynamic memory allocation • Measuring time in C

• Visual Studio 2015 IDE

4

Pointers • Pointer is a variable that stores memory address

• & operator (address operator, NOT AND operator!) • Gives memory address of a variable • * operator (NOT a multiplicaton operator!)

• Declaration of pointer variable • Gives value stored at address to which the variable points

5

Pointer example int x,y,*p;

x=3; p=&x; y=*p; *p=x+y;

What are the values of variables x,y and p during the program execution?

6

Pointers and arrays int list[4]={1,2,3,4}; int *p=list; Equivalent expressions list[2]=5;

*(p+2)=5;

p[2]=5;

*(list+2)=5;

Differences between pointers and arrays • Pointers store address of the first element, arrays store actual data • Pointers -> indirect addressing • Arrays -> direct addressing 7

Passing array as function argument • Arrays in C are passed by reference. Function gets the address of the first element of array. int sum(int *T, int n){ int s=0; while(n--){ s+=T[n]; } return s; } int main(){ const int A[]={0,1,2,3}; printf("%d\n",sum(A,(sizeof A)/ sizeof(int))); } 8

Dynamic memory allocation • The required size of the allocation is not known until run-time • e.g. array size is not known because it will be read from a file • Functions: void *malloc(size_t size); void *calloc(size_t nItems, size_t size); void *realloc(void *ptr, size_t, size); void free(void *ptr);

9

Dynamic memory allocation Example 1 int main(){ A=(int *)malloc(10*sizeof(int)); B=(double *)calloc(10,sizeof(double)); C=(char *)realloc(C,10*sizeof(char));

free(A); free(B); free(C); }

10

Dynamic memory allocation Example 2 – 2D array (matrix): int B[3][4]; int **A; int main(){ A=(int **)malloc(3*sizeof(int *)); for(int i=0;i