Fundamentals of C Programming. Simple data structures Pointers

Similar documents
Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority)

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

Keywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void

arrays C Programming Language - Arrays

Sources: On the Web: Slides will be available on:

5 Arrays and Pointers

Lecture 11 Doubly Linked Lists & Array of Linked Lists. Doubly Linked Lists

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

Informatica e Sistemi in Tempo Reale

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

1 Abstract Data Types Information Hiding

The C Programming Language course syllabus associate level

VB.NET Programming Fundamentals

Object Oriented Software Design II

Java Interview Questions and Answers

Molecular Dynamics Simulations with Applications in Soft Matter Handout 7 Memory Diagram of a Struct

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

C++ INTERVIEW QUESTIONS

Pemrograman Dasar. Basic Elements Of Java

Chapter 13 Storage classes

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

C PROGRAMMING FOR MATHEMATICAL COMPUTING

AT&T Global Network Client for Windows Product Support Matrix January 29, 2015

Embedded Programming in C/C++: Lesson-1: Programming Elements and Programming in C

How To Port A Program To Dynamic C (C) (C-Based) (Program) (For A Non Portable Program) (Un Portable) (Permanent) (Non Portable) C-Based (Programs) (Powerpoint)

JavaScript: Control Statements I

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

Arrays in Java. Working with Arrays

Coding Rules. Encoding the type of a function into the name (so-called Hungarian notation) is forbidden - it only confuses the programmer.

Answers to Review Questions Chapter 7

MISRA-C:2012 Standards Model Summary for C / C++

Illustration 1: Diagram of program function and data flow

Lecture 3. Arrays. Name of array. c[0] c[1] c[2] c[3] c[4] c[5] c[6] c[7] c[8] c[9] c[10] c[11] Position number of the element within array c

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON

COMPARISON OF FIXED & VARIABLE RATES (25 YEARS) CHARTERED BANK ADMINISTERED INTEREST RATES - PRIME BUSINESS*

COMPARISON OF FIXED & VARIABLE RATES (25 YEARS) CHARTERED BANK ADMINISTERED INTEREST RATES - PRIME BUSINESS*

Chapter 5 Names, Bindings, Type Checking, and Scopes

About The Tutorial. Audience. Prerequisites. Copyright & Disclaimer

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

Analysis One Code Desc. Transaction Amount. Fiscal Period

Memory management. Announcements. Safe user input. Function pointers. Uses of function pointers. Function pointer example

Keil C51 Cross Compiler

El Dorado Union High School District Educational Services

13 Classes & Objects with Constructors/Destructors

Tutorial on C Language Programming

1) The postfix expression for the infix expression A+B*(C+D)/F+D*E is ABCD+*F/DE*++

MS ACCESS DATABASE DATA TYPES

C++ Programming Language

In this Chapter you ll learn:

Arrays. number: Motivation. Prof. Stewart Weiss. Software Design Lecture Notes Arrays

Introduction to Data Structures

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming

IS0020 Program Design and Software Tools Midterm, Feb 24, Instruction

Comp151. Definitions & Declarations

Programming languages C

Bachelors of Computer Application Programming Principle & Algorithm (BCA-S102T)

PROGRAMMING IN C PROGRAMMING IN C CONTENT AT A GLANCE

Lecture 22: C Programming 4 Embedded Systems

Topics. Parts of a Java Program. Topics (2) CS 146. Introduction To Computers And Java Chapter Objectives To understand:

Course Title: Software Development

Phys4051: C Lecture 2 & 3. Comment Statements. C Data Types. Functions (Review) Comment Statements Variables & Operators Branching Instructions

/* File: blkcopy.c. size_t n

C Interview Questions

Data Structures using OOP C++ Lecture 1

7.1 Our Current Model

Glossary of Object Oriented Terms

Objective-C Tutorial

PROBLEMS (Cap. 4 - Istruzioni macchina)

Semantic Analysis: Types and Type Checking

Digital System Design Prof. D Roychoudhry Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

MACHINE INSTRUCTIONS AND PROGRAMS

Moving from CS 61A Scheme to CS 61B Java

JavaScript: Introduction to Scripting Pearson Education, Inc. All rights reserved.

Case 2:08-cv ABC-E Document 1-4 Filed 04/15/2008 Page 1 of 138. Exhibit 8

Multichoice Quetions 1. Atributes a. are listed in the second part of the class box b. its time is preceded by a colon. c. its default value is

3.GETTING STARTED WITH ORACLE8i

DNA Data and Program Representation. Alexandre David

1. Define: (a) Variable, (b) Constant, (c) Type, (d) Enumerated Type, (e) Identifier.

C++FA 3.1 OPTIMIZING C++

JAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system.

Java Basics: Data Types, Variables, and Loops

TCG. Trusted Platform Module Library Part 2: Structures. TCG Published. Family 2.0. Level 00 Revision October 30, 2014.

Example of a Java program

Bonus ChapteR. Objective-C

Perl in a nutshell. First CGI Script and Perl. Creating a Link to a Script. print Function. Parsing Data 4/27/2009. First CGI Script and Perl

Programming Microcontrollers in C

ASSEMBLY PROGRAMMING ON A VIRTUAL COMPUTER

Short Notes on Dynamic Memory Allocation, Pointer and Data Structure

The following themes form the major topics of this chapter: The terms and concepts related to trees (Section 5.2).

Simple C++ Programs. Engineering Problem Solving with C++, Etter/Ingber. Dev-C++ Dev-C++ Windows Friendly Exit. The C++ Programming Language

Passing 1D arrays to functions.

Fundamentals of Programming

Object Oriented Software Design

6.087 Lecture 2 January 12, 2010

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

IC4 Programmer s Manual

The programming language C. sws1 1

Chapter 2: Elements of Java

C Coding Style Guide. Technotes, HowTo Series. 1 About the C# Coding Style Guide. 2 File Organization. Version 0.3. Contents

Transcription:

Fundamentals of C Programming Simple data structures Pointers

Simple Data Structures Arrays Structures Unions

Simple Data Structures It would be limiting to have to express all data as variables. It would be desirable to be able to group data into sets of related data. This can be done two main ways: arrays (all data of the same type) structures (data may be of different types).

Type Definitions Special data types designed by the programmer can be defined through the typedef keyword. For example, if we want to define a data type that is to be defined only once and then used thereafter: typedef unsigned long int Myvar

Type Definitions So, Myvar can now be used to indicate an unsigned long int wherever used. is the same as: Myvar n; unsigned long int n; It can be used as a form of code customization and aids in making it more meaningful and readable.

Arrays Left-most symbol indicates the name of the array. This is common for all its elements. Individual data identified by distance from first one in array. Within square brackets is the cell number (how many cells away from the first one). Individual cells can be used as regular variables.

Arrays For array c: c[0] c[1] c[2] c[3] c[4] c[5] c[6] c[7] c[8] -45 6 0 72 1543-89 0 62-3

Declaring Arrays The declaration allows the compiler to set aside sufficient contiguous memory for the size of array The type of data to be stored must be identified so that sufficient space is allocated. Arrays allocated statically - remain the same size throughout program execution.

Declaring Arrays int c[12]; float a[100]; char b[15]; Can be automatic or external. Size typically done through a macro. #define SIZE 10

Initializing Arrays Not automatically initialized. Can be initialized during declaration or within the program in a loop. int n[10] = {32,27,64,18,95,14,90,70,60}; If more elements than initialized, others = 0. If less elements than initialized - error. int n[] = {32,27,64,18,95,14,90,70,60,37};

Passing Arrays to Functions Arrays passed by reference - actual variable address passed. The called function can modify the original array s values. Pass name without brackets. Include the size of the array as a passed value. Function header and prototype must indicate that an array is being passed.

Passing Arrays to Functions #define SIZE 5 void function1(int [],int); void function2(int); main() { int a[] = {0, 1, 2, 3, 4}; function1(a,size); function2(a[3]); }

Multi-dimension Arrays Arrays can have an arbitrary number of dimensions. Indicated by multiple bracket pairs. int a[5][10]; int b[10][12][20]; Can be called in same way as vector arrays. First bracket is the row script Second is the column script.

Initializing Multi-dim. Arrays Initialization by row in braces. First brace equates to first row, 2 nd to 2 nd,. int c[2][2] = {{1,2} {3,4}}; Initializes b[0][0]=1, b[0][1]=2, b[1][0]=3, and b[1][1]=4. But what if int c[2][2] = {{1} {3,4}}; Initializes b[0][0]=1, b[0][1]=0, b[1][0]=3, and b[1][1]=4.

Arrays and Strings Strings are in reality arrays of characters Each element contains one character. Each cell is one byte in size. More about strings and string operations later.

Structures A collection of related, but dissimilar variables under one name. Provides great flexibility that an array does not. Used to define records to be stored in files. Also used to form dynamic data types such as linked lists, linked stacks and linked queues.

Structure Definitions Declared as follows: struct planet { char *name; int nummoons; double dist_from_sun; float dist_from_earth; }; This creates a definition of the structure. planet is the structure tag.

Structures Components The variables are called members. They can be accessed individually using: The structure member operator (also called the dot operator). The structure pointer operator (also called the arrow operator). See Figure 10.2, page 411 of Paul and Harvey Deitel C How to program book, 7 th edition.

Structure Operators The dot operator accesses the contents of the member using the member name and the structure variable name. planet.nummoons directly accesses the contents of the member nummoons Can be used as a regular integer variable.

Structure Operators The arrow operator accesses the contents of the member using a pointer to the structure variable and the member name. planet_ptr->nummoons directly points to the contents of the member nummoons equal to (*planet_ptr).nummoons

Structure Variables The struct keyword defines a model of the desired structure. It is not a real variable per se. A real variable is created by creating an instance of the structure model. Also referred to as instantiating.

Structure Variables To make instances of the definition: Instance name(s) can be added after the definition. Can be defined as a data type to be instantiated separately. The struct keyword can be used along with the tag to instantiate. See examples next.

Structure Variables Instances added after the definition: struct planet { char *name; int nummoons; double dist_from_sun; float dist_from_earth; } earth, mars, solar[9], *ptr; solar[9] is an array of 9 structures of type planet. ptr is a pointer to a planet type.

Structure Variables The tag is optional. The following code is equivalent to the one in the last slide: struct { char *name; int nummoons; double dist_from_sun; float dist_from_earth; } earth, mars, solar[9], *ptr; Only way to instantiate is in the definition.

Structure Variables Defined as a datatype: typedef struct planet Planet; Planet earth, mars; Planet *ptr; Planet solar[9]; This assumes that the structure definition is as before.

Structure Variables Can also be done directly in the definition: typedef struct planet { char *name; int nummoons; double dist_from_sun; float dist_from_earth; } Planet; The planet tag is not necessary in this case.

Structure Variables The struct keyword can also be used to instantiate. struct planet { char *name; int nummoons; double dist_from_sun; float dist_from_earth; }; struct planet earth;

Initializing Structure Members Like in arrays. Use values inside braces. Only when variable being instantiated. struct planet earth = {earth,1,1.0e+6,0} If less values than members, then only the first few are initialized. Others = 0. Must be constant values or expressions.

Structures and Functions Structures can be passed to functions as: Individual structure members. An entire structure variable. Pointer to a structure variable. Passed by value if the individual structure member or the entire structure is passed. Passed by reference if a pointer to the structure is passed.

Structures Arrays can be assigned to a structure member. There can be arrays of structures. Structure members can be other structures. Structure members can be selfreferencing structures - pointers that point to similar structures as itself.

Unions Same as structures, except members share same storage space. Saves space when some members are never used at the same time. Space for a member must be large enough to accommodate the largest of the data types to be stored in that member.

Unions Unions are declared and defined in a way similar to structures. The keyword union replaces the keyword struct. Not highly recommended except when memory management is critical.

Enumeration Constants Allows a set of integer constants to be represented by identifiers. Symbolic constants whose value can be set automatically. Values start with 0 (unless otherwise noted by programmer) and are incremented by 1. Uses the enum keyword for definition.

Enumeration Example #include <stdio.h> enum months {JAN=1, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, ACT, NOV, DEC} main() { enum months month; char *monthname[] = {, January,..}; for(month=jan;month<=dec;month++) printf(.monthname[month]; }

Pointers

Pointer Variables Conventional variables contain values. Pointer variable contains memory address of variable that contains values (or pointers) Allows call by reference. Permits creation of dynamic data structures. Permits dynamic allocation of memory. Difficult to understand and use.

Pointer Variables Conventional variable names directly reference a value. Pointer variables indirectly reference a value Referencing a value through a pointer variable is called indirection. Pointer variables = pointers

Declaration of Pointer Variables Pointers must be declared like regular variables. It must be stated which type of variable they point to. Declarations use * to indicate pointerhood int *ptr; pointer ptr points to an integer variable.

Pointer Variables Pointers should be initialized. Can be set to NULL or to 0, but NULL is preferred. NULL is a symbolic constant defined in <stdio.h> Pointers assigned a value of 0 actually have the value 0 and not an address.

Address-of Pointer Operator Address-of operator (&) is a unary operator returning the address of its operand. The basic operator used to assign values to pointers. int y = 5; int *ptr; ptr = &y; ptr points to y (contains its address).

Indirection Pointer Operator Indirection operator (*), or dereferencing operator is also unary and returns the value of the variable pointed at by the pointer. In the previous example: y = 5 *ptr = 5 Not to be confused with the declaration operator - very confusing!!!.

Pointer Example main() { int a; int *aptr; a = 7; aptr = &a; printf( The address of a =%d,&a); printf( The value of aptr =%d, aptr); printf( The value of a = %d, *aptr); }

Call by Value Data passed by value is copied from the variable used in main() to a variable used by the function it s stored in the local variable inside the function it s value is only changed in the variable used inside the function modified inside the function

Call by Value - Example void value_funct(int); main() { int n = 5; printf( Original value = %d\n, n); value_funct(n); printf( New value = %d\n, n); } void value_funct(int n); { n = n * n; }

Call by Value - Example Original value = 5 New value = 5 The call to function value_funct did not change the original variable number in main().

Call by Reference with Pointers By passing a variable s address to a function, we give that function the ability to modify the value of the original value. This is referred to as a call by reference.

Call by Reference - Example void value_funct2(int *); main() { int number = 5; printf( Original value =, number); value_funct(&number); printf( New value =, number); } void value_funct(int *nptr); { (*nptr) = (*nptr) * (*nptr); }

Call by Reference - Example Original value = 5 New value = 25 The call to function value_funct changed the original variable number in main(). A similar effect can be obtained by value_funct returning a value to main()

Functions Returning Pointers Functions can also return pointers to variables. int* function1(int, int); is the prototype for a function that returns a pointer to an integer variable. Is easily done by simply returning the value of a pointer variable - an address.

The const and Pointer Passing The const qualifier tells the compiler that the variable following it is not to be changed by any program statements. Provides a measure of security when passing addresses of variables whose values are not to be modified (for example, arrays). When passing pointers, 4 possibilities exist:

Pointer Passing Non-constant pointer to non-constant data Declaration does not include const in any way. Data can be modified through the pointer. Pointer can be modified to point to other data. Highest level of data access to called function. This is what we have been doing up to now.

Pointer Passing Non-constant pointer to constant data: Pointer can be modified to point to any data. Data that it points to cannot be modified May be used to protect the contents of a passed array. Read as a is a pointer to an integer constant void funct(const int *a)

Pointer Passing Constant pointer to non-constant data: Pointer always points to same memory location. Data that it points to can be modified. Default value for a passed array. Pointer must be initialized when declared. Read aptr is a constant pointer to an integer int x; int * const aptr = &x;

Pointer Passing Constant pointer to constant data: Pointer always points to same memory location. Data that it points to cannot be modified. Read aptr is a constant pointer to an integer constant - right to left int x = 5; const int* const aptr = &x;

Pointer Arithmetic Pointers are valid operands in mathematical operations, assignment expressions and comparison operations. But not all operators are valid with pointers. Operators that are do not always work the same way.

Pointer Arithmetic A pointer can be incremented (++). A pointer can be decremented (--). An integer may be added to, or subtracted from a pointer (+, +=, -, -=). One pointer may be subtracted from another. But this can be misleading.

Pointer Arithmetic When adding integers to pointers, the value of the integer added is the number of memory elements to be moved. The actual answer depends on the type of memory element being pointed to by the pointer. Assuming int = 4 bytes (32 bits):

Pointer Arithmetic int *yptr = 3000; yptr += 2; In reality, yptr = 3008, because 2*4=8 bytes. In other words, the pointer moved two integer data spaces away from its original address. Since an integer data space is 4 bytes, it moved 8 bytes.

Pointer Arithmetic Since character variables are 1 byte in size, the arithmetic will be normal for pointers that point to characters. The ++ and -- operators work the same way. They add one data space to the address. int *ptr = 3000; ptr++; ptr = 3004, assuming integer takes 4 bytes.

Pointer Arithmetic Subtraction works the same way. int x; x = v1ptr - v2ptr; where v1ptr=3008 and v2ptr=3000; ==> x = 2 if int is 4 bytes.

Pointers and Arrays The name of an array is in reality a pointer to its first element. Thus, for array a[] with, for instance, 10 elements, a = &(a[0]). This is why when an array is passed to a function, its address is passed and it constitutes call by reference.

Pointers and Arrays a[3] can be also referenced as *(a+3). The 3 is called the offset to the pointer. Parenthesis needed because precedence of * is higher than that of +. Would be a[0]+3 otherwise. a+3 could be written as &a[3]. See Fig. 7.20, page 284 in textbook.

Pointers and Arrays The array name itself can be used directly in pointer arithmetic as seen before. Pointer arithmetic is meaningless outside of arrays. You cannot assume that a variable of the same type will be next to a variable in memory.

Pointers and Strings Strings are really pointers to the first element of a character array. Array is one character longer than the number of elements between the quotes. The last element is \0 (the character with the ASCII code zero).

Arrays of Pointers Arrays may contain nearly any type of variable. This includes pointers. Could be used to store a set of strings. char *suit[4] = { hearts, diamonds, spades, clubs }; The char * says that the elements of the array are pointers to char.

Arrays of Pointers Suit[0] Suit[1] Suit[2] Suit[3] H e a r t s \0 D i a m o n d s \0 C l u b s \0 S p a d e s \0

Pointers to Functions Contains address of the function in memory. This is now addressing the code segment. Can be passed to functions returned from functions stored in arrays assigned to other function pointers

Pointers to Functions Pointer contains the address of the first instruction that pertains to that function. Commonly used in menu-driven systems, where the choice made can result in calling different functions. Two examples follow:

Example 1 Writing a sorting program that orders an array of integers either in ascending or descending order. main() asks the user whether ascending or descending order, then calls the sorting function with the array name, its size and the appropriate function (ascending or descending). See Fig. 7-26, page 292 in textbook.

Example 1 - continued int ascending(int,int); int descending(int,int); void sort(int *, const int, int (*)(int,int)); main() {... sort(array,10,ascending); or sort(array,10,descending);... }

Example 1 - continued void sort(int *arr, const int size, int (*compare_func) (int, int)); { if ((*compare_func)(arr[i], arr[i+1])) do something; } int ascending(const int a, const int b) { return b < a; }

Example 1 - continued main() calls sort() and passes to it the array, its size, and the function to be used. sort() receives the function and calls it under a pointer variable compare_func, with two arguments. The arguments are elements of the array, arr[i] and arr[i+1]. compare_func returns 1 if true,0 if false.

Example 2 Functions are sometimes represented as an array of pointers to functions. The functions themselves are defined as they would normally. An array of pointers is declared that contains the function names in its elements. Functions can be called by dereferencing a pointer to the appropriate cell.

Example 2 - continued void function1(int); void function2(int); void function3(int); main() { void (*f[3])(int) = {function1, function2, function3}; } f is an array of 3 pointers to functions that take an int as an argument and return void

Example 2 - continued Such functions can be called as follows: (*f[choice]) (choice)); Can be interpreted as calling the contents of the address located in the choice cell of array f, with an argument equal to the value of the integer variable choice. The parenthesis enforce the desired precedence.

Double Pointers Double pointers are commonly used when a call by reference is desired, and the variable to be modified is itself a pointer. A double pointer is a pointer to a pointer to a variable of a particular type. Declared as int **ptr Read as a pointer to a pointer to an integer.

Double Pointers ptr int

Double Pointers Deferencing a double pointer results in an address. Derefencing it again results in the value of the ultimate variable var = *(*dbl_ptr);