C Programming Basics II

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

Dynamic memory. EECS 211 Winter 2019

advanced data types (2) typedef. today advanced data types (3) enum. mon 23 sep 2002 defining your own types using typedef

CSCI 2212: Intermediate Programming / C Storage Class and Dynamic Allocation

Dynamic Data Structures. CSCI 112: Programming in C

COMP26120: Linked List in C (2018/19) Lucas Cordeiro

However, in C we can group related variables together into something called a struct.

cout << "How many numbers would you like to type? "; cin >> memsize; p = new int[memsize];

Dynamic Allocation in C

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

Pointers, Dynamic Data, and Reference Types

TI2725-C, C programming lab, course

CS11001/CS11002 Programming and Data Structures (PDS) (Theory: 3-1-0) Allocating Space

CS349/SE382 A1 C Programming Tutorial

Pointers. Memory. void foo() { }//return

CS61C : Machine Structures

Declaring Pointers. Declaration of pointers <type> *variable <type> *variable = initial-value Examples:

Memory. What is memory? How is memory organized? Storage for variables, data, code etc. Text (Code) Data (Constants) BSS (Global and static variables)

Lectures 13 & 14. memory management

CSE 333 Midterm Exam 2/14/14

Memory Allocation. General Questions

ECE 15B COMPUTER ORGANIZATION

(13-2) Dynamic Data Structures I H&K Chapter 13. Instructor - Andrew S. O Fallon CptS 121 (November 17, 2017) Washington State University

Unit IV & V Previous Papers 1 mark Answers

CS201 Some Important Definitions

Quiz 0 Review Session. October 13th, 2014

PRINCIPLES OF OPERATING SYSTEMS

Dynamic Memory Allocation

Writing Functions in C

Memory Management in C (Dynamic Strings) Personal Software Engineering

CS201- Introduction to Programming Current Quizzes

Contents of Lecture 3

Structures and Pointers

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

DAY 3. CS3600, Northeastern University. Alan Mislove

CS 11 C track: lecture 5

Short Notes of CS201

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

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

Advanced Pointer Topics

CS201 - Introduction to Programming Glossary By

CS61C Machine Structures. Lecture 4 C Structs & Memory Management. 9/5/2007 John Wawrzynek. www-inst.eecs.berkeley.edu/~cs61c/

CS61, Fall 2012 Section 2 Notes

11 'e' 'x' 'e' 'm' 'p' 'l' 'i' 'f' 'i' 'e' 'd' bool equal(const unsigned char pstr[], const char *cstr) {

EL2310 Scientific Programming

Lecture 14. No in-class files today. Homework 7 (due on Wednesday) and Project 3 (due in 10 days) posted. Questions?

CP2 Revision. theme: dynamic datatypes & data structures

CA31-1K DIS. Pointers. TA: You Lu

Dynamic Allocation in C

ECE 2035 Programming HW/SW Systems Spring problems, 5 pages Exam Three 8 April Your Name (please print clearly)

CS107 Handout 08 Spring 2007 April 9, 2007 The Ins and Outs of C Arrays

ELEC / COMP 177 Fall Some slides from Kurose and Ross, Computer Networking, 5 th Edition

Announcements. assign0 due tonight. Labs start this week. No late submissions. Very helpful for assign1

ME964 High Performance Computing for Engineering Applications

Lecture 8 Dynamic Memory Allocation

Dynamic Memory Allocation (and Multi-Dimensional Arrays)

What is Pointer? Pointer is a variable that holds a memory address, usually location of another variable.

Cpt S 122 Data Structures. Data Structures

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

CS 241 Data Organization Binary Trees

Fall 2018 Discussion 2: September 3, 2018

LOÏC CAPPANERA. 1. Memory management The variables involved in a C program can be stored either statically or dynamically.

Kurt Schmidt. October 30, 2018

o Code, executable, and process o Main memory vs. virtual memory

CMSC 313 COMPUTER ORGANIZATION & ASSEMBLY LANGUAGE PROGRAMMING LECTURE 13, FALL 2012

C PROGRAMMING Lecture 5. 1st semester

ECE 2035 Programming HW/SW Systems Fall problems, 5 pages Exam Three 28 November 2012

Memory Organization. The machine code and data associated with it are in the code segment

Data Structure Series

Final Intro to C Review

Arrays and Memory Management

CSC 2400: Computer Systems. Arrays and Strings in C

Memory Allocation in C C Programming and Software Tools. N.C. State Department of Computer Science

CS 61C: Great Ideas in Computer Architecture Introduction to C, Part III

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

Last week. Data on the stack is allocated automatically when we do a function call, and removed when we return

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

ECE 2400 Computer Systems Programming Fall 2018 Topic 6: C Dynamic Allocation

G Programming Languages - Fall 2012

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

calling a function - function-name(argument list); y = square ( z ); include parentheses even if parameter list is empty!

CSC 1600 Memory Layout for Unix Processes"

C-types: basic & constructed. C basic types: int, char, float, C constructed types: pointer, array, struct

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

COMPSCI 210 Part II Data Structure

Lists (Section 5) Lists, linked lists Implementation of lists in C Other list structures List implementation of stacks, queues, priority queues

CSC 2400: Computer Systems. Arrays and Strings in C

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

Computers Programming Course 10. Iulian Năstac

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

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

C: Arrays, and strings. Department of Computer Science College of Engineering Boise State University. September 11, /16

CMPS 105 Systems Programming. Prof. Darrell Long E2.371

CS 222: Pointers and Manual Memory Management

Arrays, Pointers and Memory Management

Pointers review. int a = 5; int *ptr = &a; cout << *ptr;

Programs in memory. The layout of memory is roughly:

CS 33. Intro to Storage Allocation. CS33 Intro to Computer Systems XXVI 1 Copyright 2017 Thomas W. Doeppner. All rights reserved.

Pointers II. Class 31

6.S096: Introduction to C/C++

Transcription:

C Programming Basics II Xianyi Zeng xzeng@utep.edu Department of Mathematical Sciences The University of Texas at El Paso. September 20, 2016.

Pointers and Passing by Address Upon declaring a variable, space in the stack is allocated to store its value. double x; The address of this chunck of storage is called the pointer to the variable. Pointer is a special data type. double *ptr x = &x; Some familiar examples: scanf("%lf",&x); printf("%lf\n",x); How to declare: double *ptr1, x, y, *ptr2=null;

Pointers and Passing by Address Pointers to different variable types are different data types. All pointers have the same size (4/8 bytes on 32/64-bit machine). A pointer is the address at the beginning of a block of memory. Pointers cannot be used uninitialized! The following will generate a run-time error. int* myptr; *myptr = 3; A correct version: int val; int* myptr = &val; *myptr = 3; Or instead, one can use dynamic memory allocation to create space in heap for a pointer at run-time.

Pointers and Passing by Address In C, function arguments are passed by value: When we call a function, variables local to this function block are created according to the argument list. Thus only the values of the arguments are passed to the function body, not the memory spaces of the arguments in the function call. Example: Consider a function that increases an integer by one: void increase int by one( int val ) { val++; } The next piece of code int a = 3; increase int by one( a ); printf("%d\n",a); will print out 3 rather than 4.

Pointers and Passing by Address Passing by address (pointer) to modify the value of an input argument: When an input argument is a pointer, the value of the address is copied. The function body can still use this address to get access to the same location in the memory. The example revisited: Consider a function that increases an integer by one: void increase int by one( int *val ) { (*val)++; } The next piece of code int a = 3; increase int by one( &a ); printf("%d\n",a); will print out 4.

Encapsulation and Structures Let s think about how do we have a function modify the value of variables: Assign the return value to this variable: a=sqrt(a); Pass by pointer: increase int by one( &a ); Declare a global variable. Encapsulate all the data and define a new data type. We will use two keywords of C: typedef: Define a new data type. typedef double my real; struct: A collection of variables of known data types. struct Books { }; char Title[255]; char Author[255]; int Year; double Price;

Encapsulation and Structures In this example, we can declare a book variable by: struct Books a book; Alternatively, we combine the two and use: typedef struct Books {... } Book; and declare a book variable by: Book a book; Note: The typedef is not required in C++.

Encapsulation and Structures Another example of typedef: Combined with enum. We can define a new variable type that can only takes finite number of possible values: typedef enum Meals { BREAKFAST; LUNCH; DINNER; } Meal; Meal my last meal = DINNER; Another example of struct: The linked list data structure. Linked list is one of the simplest structures that allow dynamic size. One visit the members one by one until the end (NULL) is hit. struct LLData { }; OtherDataType data; LLData* next lldata; Advantage: Easy to delete/insert a new element. Disadvantage: No random data access, larger overhead over arrays.

Arrays and Memory Management C uses arrays ([][][]) to assign contiguous memory space for a number of variables of the same type. int M[10][10]; struct Books mybooks[100]; To access an element of the array: scanf("%d",&m[1][2]); printf("%d\n", M[1][2]); and struct Books tempbook = mybooks[90]; mybooks[90] = mybooks[91]; mybooks[91] = tempbook;

Arrays and Memory Management Array and pointer. double x[100]; In this case, x is actually the beginning address of the array: x == &(x[0]); // is true. And x+1 is the address of x[1]: One can use: printf("%lf\n",*(x+10)); Passing an array to a function can modify its values. void somefunction( int M[][10] );

Arrays and Memory Management In previous cases, the array sizes are known at compile time. An alternative approach is to allocate spaces dynamically. malloc: Allocate a single block of requested size of bytes. double* ptr = malloc( 100 * sizeof(double) ); calloc: Allocate multiple blocks of request elements. double* ptr = calloc( 100, sizeof(double) ); it is almost equivalent to malloc plus initilization to zero. malloc and calloc allocate space on the heap and must be freed by: free( ptr ); otherwise there is a bug known as memory leak. Compare to: double ptr[100]; ptr[100] allocate space on the stack and the space is freed automatically upon destroying the variable.

C-style Strings Strings are arrays of chars that end with a null ( \0 ). It is not necessary to allocate space with exact string length: char mystring[80]; strcpy( mystring, "Today is Tuesday" ); In this case, mystring can hold up to 79 characters. Include <string.h> for several useful string operations. Get the actual length by strlen. strcpy/strcmp/strcat. These functions rely on the existence of \ or enough space for holding the target. They do not perform check on bounds. strncpy/strncmp/strncat. These functions take an additional argument, the number of characters to operate on (in an at most sense). However, they do not guarantee, for example, there is an \0 attached to the destination.