High Performance Programming Programming in C part 1

Similar documents
Dynamic memory allocation (malloc)

C BOOTCAMP DAY 2. CS3600, Northeastern University. Alan Mislove. Slides adapted from Anandha Gopalan s CS132 course at Univ.

Jagannath Institute of Management Sciences Lajpat Nagar. BCA II Sem. C Programming

CSCI 171 Chapter Outlines

High-performance computing and programming Intro to C on Unix/Linux. Uppsala universitet

EL2310 Scientific Programming

PRINCIPLES OF OPERATING SYSTEMS

Ricardo Rocha. Department of Computer Science Faculty of Sciences University of Porto

CS 61c: Great Ideas in Computer Architecture

IMPORTANT QUESTIONS IN C FOR THE INTERVIEW

Computer Programming Unit 3

mith College Computer Science CSC352 Week #7 Spring 2017 Introduction to C Dominique Thiébaut

Lecture 04 Introduction to pointers

Chapter 14. Dynamic Data Structures. Instructor: Öğr. Gör. Okan Vardarlı. Copyright 2004 Pearson Addison-Wesley. All rights reserved.

CS 0449 Sample Midterm

C Pointers. Abdelghani Bellaachia, CSCI 1121 Page: 1

EL2310 Scientific Programming

Floating-point lab deadline moved until Wednesday Today: characters, strings, scanf Characters, strings, scanf questions clicker questions

Dynamic Memory. Dynamic Memory Allocation Strings. September 18, 2017 Hassan Khosravi / Geoffrey Tien 1

Kurt Schmidt. October 30, 2018

ch = argv[i][++j]; /* why does ++j but j++ does not? */

211: Computer Architecture Summer 2016

edunepal_info

Dynamic Data Structures. CSCI 112: Programming in C

Arrays and Pointers. CSE 2031 Fall November 11, 2013

Compiling and Running a C Program in Unix

Quick review pointer basics (KR ch )

Pointers (part 1) What are pointers? EECS We have seen pointers before. scanf( %f, &inches );! 25 September 2017

The C language. Introductory course #1

CSE 303 Lecture 8. Intro to C programming

SAE1A Programming in C. Unit : I - V

The output: The address of i is 0xbf85416c. The address of main is 0x80483e4. arrays.c. 1 #include <stdio.h> 3 int main(int argc, char **argv) 4 {

C mini reference. 5 Binary numbers 12

Procedural programming with C

Arrays and Pointers. Arrays. Arrays: Example. Arrays: Definition and Access. Arrays Stored in Memory. Initialization. EECS 2031 Fall 2014.

Introduction to C. Robert Escriva. Cornell CS 4411, August 30, Geared toward programmers

CS 261 Fall C Introduction. Variables, Memory Model, Pointers, and Debugging. Mike Lam, Professor

are all acceptable. With the right compiler flags, Java/C++ style comments are also acceptable.

Final Intro to C Review

211: Computer Architecture Summer 2016

Main Program. C Programming Notes. #include <stdio.h> main() { printf( Hello ); } Comments: /* comment */ //comment. Dr. Karne Towson University

MODULE 5: Pointers, Preprocessor Directives and Data Structures

In Java we have the keyword null, which is the value of an uninitialized reference type

Actually, C provides another type of variable which allows us to do just that. These are called dynamic variables.

Variation of Pointers

Chapter 2 (Dynamic variable (i.e. pointer), Static variable)

Fall 2018 Discussion 2: September 3, 2018

Programming. Pointers, Multi-dimensional Arrays and Memory Management

ESC101N: Fundamentals of Computing End-sem st semester

CS C Primer. Tyler Szepesi. January 16, 2013

Review Topics. Final Exam Review Slides

JTSK Programming in C II C-Lab II. Lecture 3 & 4

CSCI-243 Exam 1 Review February 22, 2015 Presented by the RIT Computer Science Community

CSE 124 Discussion (10/3) C/C++ Basics

DAY 3. CS3600, Northeastern University. Alan Mislove

The C Programming Language Part 4. (with material from Dr. Bin Ren, William & Mary Computer Science, and

Content. In this chapter, you will learn:

Pointers and File Handling

Memory, Arrays & Pointers

Lecture 03 Bits, Bytes and Data Types

Outline. Lecture 1 C primer What we will cover. If-statements and blocks in Python and C. Operators in Python and C


Introduction to C. Sean Ogden. Cornell CS 4411, August 30, Geared toward programmers

Programming in C - Part 2


Introduction to C. Ayush Dubey. Cornell CS 4411, August 31, Geared toward programmers

C Introduction. Comparison w/ Java, Memory Model, and Pointers

Unit 6 Files. putchar(ch); ch = getc (fp); //Reads single character from file and advances position to next character

Content. Input Output Devices File access Function of File I/O Redirection Command-line arguments

C Programming. Course Outline. C Programming. Code: MBD101. Duration: 10 Hours. Prerequisites:

CS201- Introduction to Programming Latest Solved Mcqs from Midterm Papers May 07,2011. MIDTERM EXAMINATION Spring 2010

HISTORY OF C LANGUAGE. Facts about C. Why Use C?

Recitation 2/18/2012

COMP 2355 Introduction to Systems Programming

mith College Computer Science CSC231 Bash Labs Week #10, 11, 12 Spring 2017 Introduction to C Dominique Thiébaut

CS 11 C track: lecture 5

A Fast Review of C Essentials Part I

2/28/2018. Overview. The C Programming Language Part 4. Pointers. Pointers. Pointers. Pointers

Dynamic memory allocation

Programming in C Quick Start! Biostatistics 615 Lecture 4

CSC209H Lecture 3. Dan Zingaro. January 21, 2015

CS 61C: Great Ideas in Computer Architecture. C Arrays, Strings, More Pointers

Today s Learning Objectives

C: Pointers, Arrays, and strings. Department of Computer Science College of Engineering Boise State University. August 25, /36

Tutorial 1: Introduction to C Computer Architecture and Systems Programming ( )

Aryan College. Fundamental of C Programming. Unit I: Q1. What will be the value of the following expression? (2017) A + 9

Basic C Program: Print to stdout. Basic C Program. Basic C Program: Print to stdout. Header Files. Read argument and print. Read argument and print

Lecture07: Strings, Variable Scope, Memory Model 4/8/2013

Fundamental of Programming (C)

Programming in C and C++

ELEC 377 C Programming Tutorial. ELEC Operating Systems

Dynamic Allocation in C

CS 326 Operating Systems C Programming. Greg Benson Department of Computer Science University of San Francisco

ECE 250 / CS 250 Computer Architecture. C Programming

Unit 1: Introduction to C Language. Saurabh Khatri Lecturer Department of Computer Technology VIT, Pune

Other C materials before pointer Common library functions [Appendix of K&R] 2D array, string manipulations. <stdlib.

Dynamic Memory Allocation

Topics so far. Review. scanf/fscanf. How data is read 1/20/2011. All code handin sare at /afs/andrew/course/15/123/handin

Arrays and Memory Management

CS201 Some Important Definitions

Transcription:

High Performance Programming Programming in C part 1 Anastasia Kruchinina Uppsala University, Sweden April 18, 2017 HPP 1 / 53

C is designed on a way to provide a full control of the computer. C is the most widely used programming languages of all time. C programming language History of C Developed by Dennis Ritchie between 1969 and 1973 at Bell Labs Successor to B language The Unix system is written in C Different data types (e.g. byte, word, struct), efficient pointers HPP 2 / 53

C standarts Software developers writing in C are encouraged to conform to the standards, as doing so aids portability between compilers. C89 (ANSI C) C90 (ISO standard) C95 C99 C11 If you want to compile your programs according to the C standard C99, you should type gcc -std=c99 -pedantic-errors. HPP 3 / 53

Structure of a program #include <stdio.h> // system header files // #include "myheader.h" for your own header files int main() { printf("hello world!"); return 0; } HPP 4 / 53

Functions The syntax of a function definition: return_type function_name( parameter list ) { /* body of the function */ } Example of function declaration: void f1(); int f2(int num1, int num2); // call by value void f3(char *s); // call by reference int* f4(int* arr); // call by reference HPP 5 / 53

Functions Recursive functions: void foo() { if(expression) return; foo(); /* function calls itself */ } int main() { foo(); } HPP 6 / 53

Q/A If we run it, what will happen? void foo() { foo(); /* function calls itself */ } int main() { foo(); } Answer: runtime error During the execution the function foo() is called repeatedly and its return address is stored in the stack. After stack memory is full we will get stack overflow error. HPP 7 / 53

main function arguments #include <stdio.h> /* printf */ #include <string.h> /* strcpy */ #include <stdlib.h> /* atoi */ int main(int argc, char const *argv[]) { if(argc!= 4) {printf("usage: %s string int double\n", argv[0]); return -1;} // Usage: a.out string int double char str[10]; strcpy(str, argv[1]); int i = atoi (argv[2]); double f = atof (argv[3]); printf("%s %d %.1f\n", str, i, f); // hello 5 6.5 return 0; } We can run the program like this:./a.out hello 5 6.5 HPP 8 / 53

Input/output #include <stdio.h> int main (){ char str [80]; int i, ihex; scanf ("%s",str); // enter string printf ("Entered string %s\n", str); scanf ("%d",&i); // enter integer printf ("Entered integer %d\n", i); scanf ("%x",&ihex); // enter hexadecimal number printf ("Entered hexadecimal %x (%d)\n", ihex, ihex); HPP 9 / 53

Input/output #include <stdio.h> int main (){ double f; char ch; scanf ("%lf",&f); // enter double printf ("Entered double %.3lf\n", f); // note format %.3lf printf ("Address of f %p\n", &f); scanf (" %c",&ch); // NOTE whitespace before %c, scanf // does not skip any leading whitespace when reading char printf ("Entered char %c\n", ch); return 0;} HPP 10 / 53

if..else The syntax of a if...else statement is: if(boolean_expression) { /* code will execute if the expression is true */ } else { /* code will execute if the expression is false */ } Relational operators:!a, A&&B, A B Note: do not confuse with bitwise operators &, Logical operators: A==B, A!= B, A > B, A >= B, A < B, A <= B Note: if(a=b) is not the same as if(a==b) HPP 11 / 53

C ternary operator: if..else condition? expression1 : expression2 Meaning: if condition is true then execute expression1, otherwise execute expression2. HPP 12 / 53

C ternary operator: if..else condition? expression1 : expression2 Meaning: if condition is true then execute expression1, otherwise execute expression2. Example: int a = 36, b; b = (a == 25)? 1: -1; printf( "b = %d, ", b ); b = (a == 36)? 1: -1; printf( "b = %d\n", b ); Output: b = -1, b = 1 HPP 12 / 53

switch The syntax of a switch statement is: switch(expression) { case constant-expression : // const-expression is a constant or a character /* code */ break; // Optional case constant-expression : /* code */ break; // Optional default : // Optional /* code */ } HPP 13 / 53

Q/A #include <stdio.h> #include <stdlib.h> int main() { int i = 1, j = 2; switch(i) { case 1: printf("first\n"); case j: printf("second\n"); } return 0; } Output: compiler error since case j is not allowed HPP 14 / 53

The syntax of a for loop is: for loop for ( init; condition; increment ) { /* code */ } HPP 15 / 53

The syntax of a for loop is: for loop for ( init; condition; increment ) { /* code */ } Example of the for loop with break and continue statements: int i; for (i = 0; i < 1000; i++ ) { if(i < 5) continue; printf("%d ", i); if(i >= 10) break; } Output: 5 6 7 8 9 10 HPP 15 / 53

while loop The syntax of a while loop is: while(condition){ /* code */ } The syntax of a do...while loop is: do{ /* code */ } while(condition); HPP 16 / 53

Example: #include<stdio.h> while loop int main() { int i = 1; while(i++ < 10) { printf("%d ", i); } return 0; } Output: 2 3 4 5 6 7 8 9 10 HPP 17 / 53

Pointers C allows to a programmer directly access and manipulate computer memory. It applies also to C++. A lots of information and examples here: http://www.c4learn.com/index/pointer-c-programming/ Pointer is a variable that can hold the address of other variable: char var = B ; char *ptr = &var; sizeof operator gives size in bytes of the object or type. sizeof(expression) (or sizeof expression) sizeof(typename) HPP 18 / 53

Declare a variable Declare an integer variable: char var = B ; 254 255 256 257 258. 312. 315 var HPP 19 / 53

Declare a variable Declare an integer variable and get its size: char var = B ; printf("sizeof(var): %lu\n", sizeof(var)); // 1 byte printf("sizeof(char): %lu\n", sizeof(char)); // 1 byte 254 255 256 257 258. 312. 315 var HPP 20 / 53

The address of a variable The operator & - returns an address of a variable. Operating system decided on which memory location will be var. Operator & just returns the address of this memory location (the address of the first byte in case the representation of the variable var needs more bytes). char var = B ; printf("the address is %p \n", &var); // 0xff in hexadecimal, 255 in decimal 254 255 256 257 258. 312. 315 var HPP 21 / 53

Declare a pointer ptr: Pointers char var = B ; // allocates 1 byte of memory char *ptr; // or char* ptr; /* ptr is a variable with type char*. In our example we use 32bit system and ptr allocates 4 bytes of memory. */ 254 255 256 257 258. 312. 315 Garbage value var ptr HPP 22 / 53

Pointers Set ptr to NULL (macros for 0): char var = B ; char *ptr = 0; // char *ptr = NULL // this telling to a developer that pointer is not used 254 255 256 257 258. 312. 315 0 var ptr HPP 23 / 53

Pointers Assign an address of var to ptr: char var = B ; char *ptr = &var; // 255 254 255 256 257 258. 312. 315 255 var ptr HPP 24 / 53

Dereferencing of pointer Operator * access the content of the memory pointed by a pointer. char var = B ; char *ptr = &var; // 255 *ptr = C ; // indirect way to change a value of var 254 255 256 257 258. 312. 315 255 var ptr HPP 25 / 53

Examples: char var = A ; char *ptr = &var; // var = A char var2 = *ptr; // var = A, var2 = A *ptr = B ; // var = B, var2 = A var = C ; // var = C, var2 = A ptr = &var2; *ptr = D ; // var = C, var2 = D HPP 26 / 53

Q/A What is the output of the following code: int a = 2, b = 3; int *p1 = &a; int *p2 = &b; *p1 = b; *p2 = a; printf("%d, %d", a, b); Answer: 3, 3 HPP 27 / 53

Pointer arithmetics See here for explanation and examples: http://www.c4learn. com/c-programming/c-pointer-arithmetic-operations/ p and r are pointers Operator precedence: p++ gives pointer to the next variable p - r get distance between pointers p + 5 moves pointer 5 positions forward p + r not supported Operator precedence: *p++ increment pointer not value pointed by it (*p)++ increment value pointed by p HPP 28 / 53

#include <stdio.h> Q/A void f ( int *a, int b ) { int *c; c = &b; (*a)++; b++; (*c)++; } int main () { int a = 1, b = 10, c = 100; f (&a, b ); printf( "a = %d, b = %d, c = %d\n", a, b, c ); return 0 ; } HPP 29 / 53

Pointers Write a function which sets pointer to a given value. What should be insteads of??... int *x; tonull(? x, 3);... void set(? x, int n ) {? x = n; } (See answer on the next slide) HPP 30 / 53

Pointers Write a function which sets pointer to a given value.... int *x; tonull(&x, 3);... void set( int **x, int n) { *x = n; } HPP 31 / 53

Structures Declare a structure with 2 members: struct person { char name[50]; int age; }; If we want to define an object: struct person A; To access a member: A.age = 19; Define a shortcut person t for struct person using typedef: typedef struct person person_t; HPP 32 / 53

Pointers and structures struct person { char name[50]; int age; }; typedef struct person person_t; person_t A; // or struct person A; A.age = 18; // set values of the structure members strcpy(a.name, "Maria"); HPP 33 / 53

Pointers and structures struct person { char name[50]; int age; }; typedef struct person person_t; person_t *A = (person_t *)malloc(sizeof(person_t)); // pointer to a structure (*A).age = 18; // set values of the structure members strcpy((*a).name, "Maria"); //or A->age = 18; // set values of the structure members strcpy(a->name, "Maria"); HPP 34 / 53

Pointers A lots of information and examples here: http://www.c4learn.com/index/pointer-c-programming/ Check this short summary about the pointers: http://nuclear.mutantstargoat.com/articles/pointers_ explained.pdf Here you can read also about void pointers which can keep an address of the variable but cannot be dereferenced! HPP 35 / 53

Arrays T[n] is an array of n elements of type T: 0,..., n 1 Arrays values are stored in contiguous memory locations. Initialization: type arrayname [ size ]; // size is a constant! double balance[5] = {1000.0, 2.0, 3.4, 7.0, 50.0}; //or double balance[] = {1000.0, 2.0, 3.4, 7.0, 50.0}; HPP 36 / 53

Arrays Arrays are closely related to pointers. int a[] = {1, 2, 3, 4}; int *p = a; // pointer to the first element // equivalent: int *p = &a[0]; // pointer to the first element int *p = &a[3]; // pointer to the fourth element Moreover: int *p = a+2; // pointer to the third element int v = *(a+2); // the third element HPP 37 / 53

Arrays Program writing in the standard output elements of the array arr: #include <stdio.h> int main() { int arr[5] = {11,22,33,44,55}; int i; for(i=0;i<5;i++) { printf("%d ",arr[i]); // or printf("%d ",*(arr + i)); } return 0; } HPP 38 / 53

String literal String literal: "hello", "this is a string" Note: character: a, string "a" Staring literal has a type const char[size] The null character ( \0 ) is always appended to the string literal: "hello" is a const char[6] holding the characters H, e, l, l, o, and \0. On the compilation phase "Hello," " world!" yields the string "Hello, world!" HPP 39 / 53

String literal and array of char String literals can be assigned to char arrays: char array1[] = "Hello" "world"; // same as char array2[] = { H, e, l, l, o, w, o, r, l, d, \0 }; Common functions: strlen gives number of characters in the string, computed at the run time sizeof gives size of the array, computed at the compile time HPP 40 / 53

Strings char arr[] = "Hello world"; int len = strlen(arr); where size_t strlen ( const char * str ); Implicit cast from array type char[] to the pointer to char char*. Function gets the pointer to the first element of the array. How does strlen knows the size of str? HPP 41 / 53

Strings char arr[] = "Hello world"; int len = strlen(arr); where size_t strlen ( const char * str ); Implicit cast from array type char[] to the pointer to char char*. Function gets the pointer to the first element of the array. How does strlen knows the size of str? (String ends with a terminating null character \0 ) int len = strlen(arr); // answer is 11 HPP 41 / 53

Strings What is the output of the following program? #include<stdio.h> int main() { char s[20] = "Hello\0Hi"; printf("%d %d", strlen(s), sizeof(s)); } Answer: 5 20 strlen given the length of a string, so it is counting characters up to 0. sizeof reports the size of the array. HPP 42 / 53

Strings strcpy copies the string pointed by source into the array pointed by destination: char * strcpy ( char * destination, const char * source ); Example: char a[4]; //a = "hello"; strcpy(a, "hello"); This is an error! // This is correct! HPP 43 / 53

Q/A #include <stdio.h> int main() { int *ptr, m = 100; ptr = &m ; printf("%p",ptr); return 0; } Output: address of the variable m HPP 44 / 53

Q/A #include<stdio.h> void foo(int *num1, int *num2) { int temp; temp = *num1; *num1 = *num2; *num2 = temp; } int main() { int x=1, y=2; foo(&x, &y); printf("%d %d", x, y); return 0; } Output: 2 1 HPP 45 / 53

Static vs dynamic memory Static memory allocation: memory is allocated by the compiler. Dynamic memory allocation: memory is allocated at the time of run time on heap. You would use DMA if you don t know exactly how much data you will need at runtime or if you need to allocate a lot of data. Static allocation: int arr[10]; Dynamic allocation int *ptr; ptr=(int *)malloc(sizeof(int)*10); HPP 46 / 53

malloc, calloc, realloc from <stdlib.h> malloc is used to allocate an amount of memory of size bytes during the execution of a program. void* malloc (size_t size_of_block); calloc allocates and zero-initialize array void* calloc (size_t number_of_elements, size_t size_of_each_element); realloc changes the size of the memory block pointed to by ptr void* realloc (void* ptr_to_block, size_t size_of_block); All functions return pointer to the allocated memory block. HPP 47 / 53

free(p) No garbage collector in C! You must free memory allocated with malloc, calloc or realloc using void free (void* ptr); A memory leak occurs when dynamically allocated memory has become unreachable. Typical program: int *ptr = (int *)malloc(sizeof(int)); if (ptr == 0) { printf("error: Out of memory\n"); return 1;} /* code used ptr*/ free(ptr); HPP 48 / 53

Q/A Think before next lecture: 1. Can I increase the size of dynamically allocated array? 2. If you pass an array as an argument to a function, what is actually passed? HPP 49 / 53

File I/O A file represents a sequence of bytes, regardless of it being a text file or a binary file. FILE *fopen( const char *filename, const char *mode ) filename is a string literal, the name of a file. Most common file modes: r : Opens an existing text file for reading purpose. w : Opens a text file for writing. If it does not exist, then a new file is created. Function returns NULL pointer if file cannot be opened. Close file: int fclose( FILE *fp ); HPP 50 / 53

File I/O Example #include <stdio.h> int main() { FILE *fp1; // POINTER to an object FILE FILE *fp2; char buff[255]; fp1 = fopen("test.txt", "r"); // open file test.txt for reading fp2 = fopen("out.txt", "w"); // open file out.txt for writing fscanf(fp1, "%s", buff); // read a string to buff (reads untill the space is encountered) fprintf(fp2, "%s", buff); // write data from buff to the file fp2 fclose(fp1); fclose(fp2); return 0; } See also here: https: //www.tutorialspoint.com/cprogramming/c_file_io.htm HPP 51 / 53

Summary What do you know after the lecture: syntax of basic constructions of C programming language what is a pointer and how to use it how to operate with strings and arrays how to allocate memory dynamically during runtime Lab02 is available on the Studentportalen. HPP 52 / 53

What is next? It is important to understand the material of this lecture before the next lecture! What will we do on the next lecture? how to use multidimensional arrays how to measure time in C what is time and space complexity data structures (binary tree, linked list and maybe some other) HPP 53 / 53