Structures and Pointers

Similar documents
Design and development of embedded systems for the Internet of Things (IoT) Fabio Angeletti Fabrizio Gattuso

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

CS349/SE382 A1 C Programming Tutorial

Arrays and Pointers (part 1)

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

CS 11 C track: lecture 5

} Evaluate the following expressions: 1. int x = 5 / 2 + 2; 2. int x = / 2; 3. int x = 5 / ; 4. double x = 5 / 2.

Arrays and Pointers (part 1)

Recap. ANSI C Reserved Words C++ Multimedia Programming Lecture 2. Erwin M. Bakker Joachim Rijsdam

Darshan Institute of Engineering & Technology for Diploma Studies Unit 5

Complex data structures. Cedric Saule

EL2310 Scientific Programming

Variation of Pointers

CprE 288 Introduction to Embedded Systems Exam 1 Review. 1

Laboratory 10 POINTERS I. FUNDAMENTALS

Deep C. Multifile projects Getting it running Data types Typecasting Memory management Pointers. CS-343 Operating Systems

Dynamic Data Structures. CSCI 112: Programming in C

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

Arrays and Pointers. CSE 2031 Fall November 11, 2013

Class Information ANNOUCEMENTS

At this time we have all the pieces necessary to allocate memory for an array dynamically. Following our example, we allocate N integers as follows:

Introduction to C. Zhiyuan Teo. Cornell CS 4411, August 26, Geared toward programmers

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

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

Chapter 7. Pointers. Copyright 2007 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

CSCI 171 Chapter Outlines

Pointers, Dynamic Data, and Reference Types

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

22c:111 Programming Language Concepts. Fall Types I

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

CS113: Lecture 5. Topics: Pointers. Pointers and Activation Records

Data Types and Variables in C language

Arrays, Pointers and Memory Management

Heap Arrays. Steven R. Bagley

Review: C Strings. A string in C is just an array of characters. Lecture #4 C Strings, Arrays, & Malloc

Data Representation and Storage. Some definitions (in C)

What is an algorithm?

Heap Arrays and Linked Lists. Steven R. Bagley

Procedural programming with C

Data Structures Lecture 2 : Part 1: Programming Methodologies Part 2: Memory Management

Objectives. Describe ways to create constants const readonly enum

a data type is Types

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

Lecture 12. Data Types and Strings

Lecture 3. The syntax for accessing a struct member is

Pointer Basics. Lecture 13 COP 3014 Spring March 28, 2018

Memory Management. a C view. Dr Alun Moon KF5010. Computer Science. Dr Alun Moon (Computer Science) Memory Management KF / 24

Intermediate Programming, Spring 2017*

CS24 Week 2 Lecture 1

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

C Programming Basics II

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

Week 9 Part 1. Kyle Dewey. Tuesday, August 28, 12

CS 222: Pointers and Manual Memory Management

Warmup January 9th, What is the value of the following C expression? 8*9 % 10/ 2

Dynamic Allocation in C

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

Lecture 8 Dynamic Memory Allocation

Review of the C Programming Language for Principles of Operating Systems

C for Java Programmers 1. Last Week. Overview of the differences between C and Java. The C language (keywords, types, functies, etc.

CSC 1600 Memory Layout for Unix Processes"

Tokens, Expressions and Control Structures

Generic Swap. void swap (void *ap, void *bp, int size) { char temp[size]; memcpy (temp, ap, size); memcpy (ap, bp, size); memcpy (bp, temp, size); }

MYcsvtu Notes LECTURE 34. POINTERS

Short Notes of CS201

Dynamic Memory Management. Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island

Understanding Pointers

C C C C++ 2 ( ) C C++ 4 C C

Arrays and Memory Management

CS201 - Introduction to Programming Glossary By

TYPES, VALUES AND DECLARATIONS

Lecture 5: Multidimensional Arrays. Wednesday, 11 February 2009

C: Pointers. C: Pointers. Department of Computer Science College of Engineering Boise State University. September 11, /21

Memory Management. CSC215 Lecture

Fundamental of C programming. - Ompal Singh

ECE 2400 Computer Systems Programming Fall 2018 Topic 7: Concrete Data Types

Pointers. A pointer is simply a reference to a variable/object. Compilers automatically generate code to store/retrieve variables from memory

C Pointers. Abdelghani Bellaachia, CSCI 1121 Page: 1

Pointers. Addresses in Memory. Exam 1 on July 18, :00-11:40am

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

ECE 15B COMPUTER ORGANIZATION

[0569] p 0318 garbage

Programming. Pointers, Multi-dimensional Arrays and Memory Management

Pointers. A pointer value is the address of the first byte of the pointed object in the memory. A pointer does not know how many bytes it points to.

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

A3-R3: PROGRAMMING AND PROBLEM SOLVING THROUGH 'C' LANGUAGE

CS 61C: Great Ideas in Computer Architecture C Pointers. Instructors: Vladimir Stojanovic & Nicholas Weaver

Types. What is a type?

MODULE 5: Pointers, Preprocessor Directives and Data Structures

Kurt Schmidt. October 30, 2018

ME964 High Performance Computing for Engineering Applications

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

SYSC 2006 C Winter 2012

Data Representation and Storage

CS61C : Machine Structures

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010

Other conditional and loop constructs. Fundamentals of Computer Science Keith Vertanen

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

12 CREATING NEW TYPES

CSCI312 Principles of Programming Languages!

Transcription:

Structures and Pointers Comp-206 : Introduction to Software Systems Lecture 11 Alexandre Denault Computer Science McGill University Fall 2006

Note on Assignment 1 Please note that handin does not allow you to hand in a file whose name starts with a period ex:.bash_profile You will have to rename that file before handing it in ex: bash_profile

Pass by reference, pass by value Primitives (such as int, short, long, float, etc) are passed by value. This means you can change their value in a function and they will not be affected. Arrays are passed by value. This means that if you change the values in an array, it will affect the whole application. Pointers, which we will see in a couple of lectures, complicate this even more. void testfunction(int a, int myarray[]) { a = 10; // No effect to rest of application myarray[0] = 10; // Affects rest of app. }

Structures Structures are a data type composed of several other data types. Think of it as a container, a variable that has variables inside it. You can define new structures using the struct keyword. struct course { int number_of_students; char[100] name_professor; char[100] location_building; int location_room; }

Using a structure To use a structure, you need to instantiate a copy of it. All you need to do is to declare the variable for the instance. struct course cs206; You can then fill it with data. cs206.number_of_student = 60; cs206.name_professor = Alex ; cs206.location_building = MacDonald ; cs206.location_room = 328; With structures, you can declare the variable and initialize it with data in one command. struct course cs206 = {60, Alex, MacDonald, 328);

typedef and struct You can use typedef to define the structure as a new type. typedef struct course { int number_of_students; char[100] name_professor; char[100] location_building; int location_room; } When creating a variable of this type, you no longer need to specify the struct keyword. struct course cs206;

Coercion or Type-Casting Coercion : forcing one variable of one type to be another type. Sometimes, type-casting is implicit : int a = 2; float b = a; // b = 2.0 Most of the time, it's safer to specify it: float a = 3.1415; int b = (int)a; // b = 3 When in doubt, type cast: int a = 2; float b = 3 / a; // b = 1.0 float c = 3 / (float)a; // c = 1.5

Enumerated Types Enumerated types : contain a list of constants that can be addressed in integer values. enum days {monday, tuesday, wednesday, thursday, friday, saturday, sunday}; As with arrays first enumerated name has index value 0. So monday has value 0, tuesday 1,... We can also override the 0 start value: enum days {monday = 1, tuesday, wednesday, thursday, friday, saturday, sunday}; Or simply assign different numerical values: enum days {monday = 10, tuesday = 20, wednesday = 30, thursday = 40, friday = 50, saturday = 60, sunday = 0};

Using Enumerations Creating a variable of an enumeration is similar to a structure: enum days week1; If you typedef an enumerated type, you can use it without the enum keyword. typedef enum days {monday = 1, tuesday, wednesday, thursday, friday, saturday, sunday}; days week1;

Static Variables Static Variable : variable local to particular function but only initialized once (on the first call to function). function int count() { static int counter = 0; counter++; return counter; } The following function will count the number of time it is called. The same count have been done with a global variable, but counter doesn't need global visibility.

Pointers One of the most difficult feature of C. Also one of the most fundamental and important feature. Pointers exist of efficiency and flexibility reasons. They are used explicitly with Functions Arrays Structures

What are pointers? A pointer is a variable which contains the address in memory of another variable. Think of it as an integer variable that points to a block of memory. We can have a pointer to any variable type.

Pointer operators The unary or monadic operator & gives the address of a variable. The indirection or dereference operator * gives the contents of an object pointed to by a pointer. Pointers are declared using the indirection operator: int* a;

Simple Pointer Example int a, b; int* p; a = 5; b = 10; p = &a; // p is pointing on a *p = 6; // Value of a is now 6; p = &b; // p is pointing on b *p = 11; // Value of b is now 11;

Pointers and Functions The following functions cannot be implemented without pointers: void swap(int a, int b) { int temp = a; a = b; b = temp; } This function only alters the value of the local variables a and b. The change is invisible to the calling function. int a = 5, b = 10; swap (a,b);

A look into memory a : a10 b : 5 a a: 5 b : 10 memory of swap function memory of function calling swap

Swap using pointers The following function does work, because it uses pointers to the integers. void swap (int * pa, int * pb) { int temp = *pa; *pa = *pb; *pb = temp; } When calling the swap function, the address the integers must be provided: int a = 5, b = 10; swap (&a,&b);

Using pointers instead pa : pb : a : a10 b : 5 memory of swap function memory of function calling swap

Pointers and Arrays Arrays and pointers are very related in C. In fact, when you create an array in C, you allocate a block of memory and create a pointer to the first element of that block of memory. int a[10]; a

Dynamic Memory Allocation The malloc() function allocates a block of memory and returns a pointer to that allocated memory. void *malloc(size_t size); The size of the block must be specified. That block memory is not initialized. It will contain whatever is currently in memory. Be careful not to access memory outside what you allocated. Nothing will prevents you from accessing outside that block of memory.

Using the blocks of memory Both malloc and calloc return a void pointer (void *). In C, you use a void* when return a generic pointer. This generic block of memory must be cast before it can be used. int *a = (int *) malloc( sizeof(int) * 40 ); The sizeof() function simplifies the allocation of memory by calculating the size of the provided data type.

Deallocating Memory The free() function releases the specified memory space. void free(void *ptr); The specified memory must have been returned by a previous call to malloc(), calloc() or realloc(). Otherwise, undefined behavior occurs. Not releasing memory after finishing with it can create memory leaks. This can be an especially serious problem if you continually allocate memory.