Using pointers with functions

Similar documents
Arrays and pointers. *(anarray + n) is equivalent to anarray[n], where n is an integer. EE 285 pointers and arrays 1

Chapter 6 - Pointers

Writing to and reading from files

C Pointers. sizeof Returns size of operand in bytes For arrays: size of 1 element * number of elements if sizeof( int ) equals 4 bytes, then

Chapter 7 C Pointers

Programming Assignment #4 Arrays and Pointers

Pointers. Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan

Solutions to Chapter 8

Lecture 05 POINTERS 1

Outline. Computer Memory Structure Addressing Concept Introduction to Pointer Pointer Manipulation Summary

Two Dimensional Array - An array with a multiple indexs.

ECE264 Fall 2013 Exam 1, September 24, 2013

Lecture 04 FUNCTIONS AND ARRAYS

ECE 2400 Computer Systems Programming Fall 2017 Topic 4: C Pointers

Computer Science & Engineering 150A Problem Solving Using Computers

SYSC 2006 C Winter 2012

CS 137 Part 8. Merge Sort, Quick Sort, Binary Search. November 20th, 2017

Two Dimensional Array - An array with a multiple indexs.

CS 106 Introduction to Computer Science I

cs3157: another C lecture (mon-21-feb-2005) C pre-processor (3).

Intermediate Programming, Spring 2017*

Intermediate Programming, Spring 2017*

AMCAT Automata Coding Sample Questions And Answers

Pointers as Arguments

Fundamentals of Programming Session 20

C Pointers Pearson Education, Inc. All rights reserved.

C Programming Language

Singly linked lists in C.

Structured programming

C Review. MaxMSP Developers Workshop Summer 2009 CNMAT

CS3157: Advanced Programming. Outline

Content. In this chapter, you will learn:

by Pearson Education, Inc. All Rights Reserved.

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

C++ PROGRAMMING SKILLS Part 4: Arrays

(Refer Slide Time: 00:23)

Declaration of Statically-Allocated Arrays

Intermediate Programming, Spring 2017*

C Arrays. Group of consecutive memory locations Same name and type. Array name + position number. Array elements are like normal variables

Exercise 3 / Ch.7. Given the following array, write code to initialize all the elements to 0: int ed[100]; Hint: It can be done two different ways!

ESC101N Fundamentals of Computing

C Arrays Pearson Education, Inc. All rights reserved.

Operating Systems 2INC0 C course Pointer Advanced. Dr. Ir. Ion Barosan

Pointers and Strings. Adhi Harmoko S, M.Komp

Principles of C and Memory Management

Agenda. Peer Instruction Question 1. Peer Instruction Answer 1. Peer Instruction Question 2 6/22/2011

Lecture 6 Sorting and Searching

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

ECE 15B COMPUTER ORGANIZATION

First of all, it is a variable, just like other variables you studied

ECE264 Spring 2013 Final Exam, April 30, 2013

Character Array. C Programming. String. A sequence of characters The last character should be \0 that indicates the end of string 5 \0

Subject: Fundamental of Computer Programming 2068

Problem: Read 10 numbers from the keyboard and store them

Advanced Pointer Topics

today cs3157-fall2002-sklar-lect05 1

Exercise 1.1 Hello world

Variables Data types Variable I/O. C introduction. Variables. Variables 1 / 14

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

Tutorial 1: C-Language

ECE264 Spring 2014 Exam 2, March 11, 2014

POINTERS. Content. Pointers. Benefits of Pointers. In this chapter, you will learn:

Tutorial 10 Pointers in C. Shuyue Hu

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

APS105. Collecting Elements 10/20/2013. Declaring an Array in C. How to collect elements of the same type? Arrays. General form: Example:

Sorting Algorithms part 1

Initialisation of an array is the process of assigning initial values. Typically declaration and initialisation are combined.

Output of sample program: Size of a short is 2 Size of a int is 4 Size of a double is 8

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

Agenda. Components of a Computer. Computer Memory Type Name Addr Value. Pointer Type. Pointers. CS 61C: Great Ideas in Computer Architecture

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

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

CS 61C: Great Ideas in Computer Architecture. Lecture 3: Pointers. Krste Asanović & Randy Katz

Data Representation and Storage. Some definitions (in C)

Language comparison. C has pointers. Java has references. C++ has pointers and references

CS132 Algorithm. Instructor: Jialiang Lu Office: Information Center 703

Algorithm efficiency can be measured in terms of: Time Space Other resources such as processors, network packets, etc.

Sample Examination. Family Name:... Other Names:... Signature:... Student Number:...

Before we start - Announcements: There will be a LAB TONIGHT from 5:30 6:30 in CAMP 172. In compensation, no class on Friday, Jan. 31.

COP 3223 Final Review

SCJ2013 Data Structure & Algorithms. Bubble Sort. Nor Bahiah Hj Ahmad & Dayang Norhayati A. Jawawi

ECE264 Fall 2013 Exam 2, October 24, 2013

LECTURE 17. Array Searching and Sorting

UNIVERSITY OF MALTA FACULTY OF INFORMATION AND COMMUNICATION TECHNOLOGY Department of Computer Information Systems

Arrays and Pointers in C & C++

Submit your answers to these questions to the Curator under Quizzes as HW08 by the posted due date and time. No late submissions will be accepted.

CS 137 Part 7. Big-Oh Notation, Linear Searching and Basic Sorting Algorithms. November 10th, 2017

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

CSCI2467: Systems Programming Concepts

One Dimension Arrays 1

Data Types. Data Types. Integer Types. Signed Integers

Binary Representation. Decimal Representation. Hexadecimal Representation. Binary to Hexadecimal

Decimal Representation

Outline Introduction Arrays Declaring Arrays Examples Using Arrays Passing Arrays to Functions Sorting Arrays

Lecture 04 Introduction to pointers

Intermediate Programming, Spring 2017*

C Pointers. CS 2060 Week 6. Prof. Jonathan Ventura

Pointers and Structure. Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island

The University Of Michigan. EECS402 Lecture 07. Andrew M. Morgan. Sorting Arrays. Element Order Of Arrays

Chapter 10 - Notes Applications of Arrays

Transcription:

Using pointers with functions Recall that our basic use of functions so fare provides for several possibilities. A function can 1. take one or more individual variables as inputs and return a single variable as the output. 2. take no inputs (void) and a single variable as an output. 3. take one or more individual variables as inputs and not return anything as an output (void). 4. take no inputs (void) and not return anything as any output (void) What s missing in this initial list of things that functions can do is being able to take arrays as inputs and being able to return more than one value as an output. (This would include returning arrays as outputs.) EE 285 pointers and arrays 1

To get some sense of the problem, let s try to make a function that would swap two integers in memory. We have needed this in several instances and it might be nice to have a re-usable function that does it. //EE 285 - swap (bad) void swap( int, int ); int x = 3, y = 8; printf( "Before swapping: x = %d and y = %d.\n\n", x, y ); swap( x, y ); printf( "After swapping: x = %d and y = %d.\n\n", x, y ); void swap( int a, int b ){ int temp; temp = a; a = b; b = temp; Before swapping: x = 3 and y = 8. After swapping: x = 3 and y = 8. Urk!! That didn't work. EE 285 pointers and arrays 2

To debug what went wrong, we can add a couple of printf statements to the function. void swap( int a, int b ){ int temp; printf( "Before swapping: a = %d and b = %d.\n", a, b ); temp = a; a = b; b = temp; printf( " After swapping: a = %d and b = %d.\n", a, b ); Before swapping: x = 3 and y = 8. Before swapping: a = 3 and b = 8. After swapping: a = 8 and b = 3. After swapping: x = 3 and y = 8. So we see that the swapping function is working, but the results are not getting back to main. Actually, this should not surprise us at all, once we consider what is going on in memory. EE 285 pointers and arrays 3

x 3 x 3 x 3 x 8 x 8 x 8 y 3 y 3 a 3 a 3 a 8 a 8 b 8 b 8 b 8 b 3 temp temp 3 temp 3 temp 3 Oops! The swapping was localized to the function. Nothing happened back in the main. This was a waste of time. EE 285 pointers and arrays 4

A light bulb goes off! In the function, try using pointers to the original variables. &x x 3 x 3 x 3 x 8 x 8 x 8 &y y 3 y 3 &x &x &x &x &y &y &y &y temp temp 3 temp 3 temp 3 Now it would work! Of course, the code must be modified to pass pointers instead. EE 285 pointers and arrays 5

//EE 285 - swap (good) void swap( int*, int* ); int x = 3, y = 8; printf( "Before swapping: x = %d and y = %d.\n\n", x, y ); swap( &x, &y ); printf( "After swapping: x = %d and y = %d.\n\n", x, y ); void swap( int *aptr, int *bptr ){ int temp; temp = *aptr; *aptr = *bptr; *bptr = temp; Before swapping: x = 3 and y = 8. After swapping: x = 8 and y = 3. Yay! The realization that we can pass pointers to ( and from) functions greatly expands our capabilities. Using pointers, we can "receive" more than one variable from the function. Even better, we can pass (and receive) pointers to arrays. Now we can really start doing some things. EE 285 pointers and arrays 6

Pass a pointer to an array. //EE 285 - max of an array int max( int*, int ); int anarray[] = { 4, 8, 3, 9, 2, 1, 10, 6, 5, 72, 0 ; int maxvalue; maxvalue = max( anarray, 11 ); printf( "The maximum value is %d.\n\n", maxvalue ); int max( int a[], int size ){ int i, biggie = 0; for(i = 0; i < size; i++ ) if( a[i] > biggie) biggie = a[i]; return biggie; The maximum value is 72. EE 285 pointers and arrays 7

//EE 285 - average of an array double average( int*, int ); int anarray[] = { 4, 8, 3, 9, 2, 1, 10, 6, 5, 12, 0 ; double avgvalue; avgvalue = average( anarray, 11 ); printf( "The average value is %5.3lf.\n\n", avgvalue ); double average( int* aptr, int size ){ int i; double sum = 0; for(i = 0; i < size; i++ ) sum = sum + *(aptr + i); return sum/size; The average value is 5.455. EE 285 pointers and arrays 8

Use functions to bubble sort an array. (Bubble sort function is on following page.) //EE 285 - bubble sort an array void bubblesort( int*, int ); void printarray( int*, int ); int anarray[] = { 4, 8, 3, 9, 2, 1, 10, 6, 5, 12, 0 ; printarray( anarray, 11 ); bubblesort( anarray, 11 ); printarray( anarray, 11 ); /* printarray function */ void printarray( int a[], int size ){ int i; printf( "The array is { " ); for(i = 0; i < size ; i++ ) printf( "%d ", a[i] ); printf( "\n\n" ); EE 285 pointers and arrays 9

/* bubblesort function */ void bubblesort( int a[], int size ){ int i, j, swap; for(i = 0; i < size - 1 ; i++ ){ for( j = 0; j < size - 1; j++){ if( a[j+1] > a[j] ){ swap = a[j]; a[j] = a[j+1]; a[j+1] = swap; The array is { 4 8 3 9 2 1 10 6 5 12 0 The array is { 12 10 9 8 6 5 4 3 2 1 0 EE 285 pointers and arrays 10

Write a function that generates a string with random characters. (main() is below and the functions are on the next page.) //EE 285 - generate a random array #include <stdlib.h> #include <time.h> void randchararray( char*, int ); void printchararray( char* ); const int SIZE = 11; char carray[ SIZE ]; //10 characters + '\0' srand( (int)time(0) ); randchararray( carray, SIZE ); printchararray( carray ); Note: Printable ASCII characters have decimal values from 32 to 126. (ASCII code 32 coresponds to space. See https://en.wikipedia.org/ wiki/ascii. ) EE 285 pointers and arrays 11

/* print a character array */ void printchararray( char a[] ){ int i = 0; printf( "The array is: " ); while( a[i]!= '\0' ){ printf( "%c ", a[i] ); i++; printf( "\n\n" ); /* generate random character array */ void randchararray( char a[], int s ){ int i; for(i = 0; i < s - 1 ; i++ ) a[i] = rand()%94 + 32; a[i] = '\0'; //Add the trailing 0. The array is: 7 U # Q n < y 3 z EE 285 pointers and arrays 12

//EE 285 - bubble sort an array void bubblesort( int*, int ); void printarray( int*, int ); Sizeof function Use this to get the size (number of bytes) of something stored in memory. With this, we do not need to know ahead of time how big an array is. Below is the bubble sort main() that uses sizeof() to figure out how big (how many elements) are in the array. The functions are unchanged and not included below. int anarray[] = { 4, 8, 3, 9, 2, 1, 10, 6, 5, 12, 0 ; int length; length = sizeof(anarray) / sizeof(anarray[0]); printf( "The array size is %d.\n\n", length ); printarray( anarray, length ); bubblesort( anarray, length ); printarray( anarray, length ); The array size is 11. The array is { 4 8 3 9 2 1 10 6 5 12 0 The array is { 12 10 9 8 6 5 4 3 2 1 0 EE 285 pointers and arrays 13