void setup(){ void loop() { The above setup works, however the function is limited in the fact it can not be reused easily. To make the code more gene

Similar documents
Pointers in C/C++ 1 Memory Addresses 2

Arrays and Pointers in C. Alan L. Cox

C Praktikum. Advanced Pointers. Eugen Betke, Nathanael Hübbe, Michael Kuhn, Jakob Lüttgau, Jannek Squar

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

Pointers. 1 Background. 1.1 Variables and Memory. 1.2 Motivating Pointers Massachusetts Institute of Technology

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

CSC 211 Intermediate Programming. Arrays & Pointers

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:

QUIZ. 1. Explain the meaning of the angle brackets in the declaration of v below:

PIC 10A Pointers, Arrays, and Dynamic Memory Allocation. Ernest Ryu UCLA Mathematics

Introduction to C: Pointers

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #44. Multidimensional Array and pointers

Programming Studio #9 ECE 190

Heap Arrays. Steven R. Bagley

CS 230 Programming Languages

1d: tests knowing about bitwise fields and union/struct differences.

Introduction to C++ Introduction. Structure of a C++ Program. Structure of a C++ Program. C++ widely-used general-purpose programming language

Computer Systems C S Cynthia Lee

Assignment 1: grid. Due November 20, 11:59 PM Introduction

Software Engineering Concepts: Invariants Silently Written & Called Functions Simple Class Example

Lecture 4: Outline. Arrays. I. Pointers II. III. Pointer arithmetic IV. Strings

Arrays, Pointers and Memory Management

Introduction to C++ with content from

Today s lecture. Pointers/arrays. Stack versus heap allocation CULTURE FACT: IN CODE, IT S NOT CONSIDERED RUDE TO POINT.

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

AMCAT Automata Coding Sample Questions And Answers

Outline. Pointers arithme.c and others Func.ons & pointers

Computers Programming Course 6. Iulian Năstac

Arrays and Pointers in C & C++

CE221 Programming in C++ Part 2 References and Pointers, Arrays and Strings

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

CS61C Machine Structures. Lecture 4 C Pointers and Arrays. 1/25/2006 John Wawrzynek. www-inst.eecs.berkeley.edu/~cs61c/

Variables and literals

Memory, Data, & Addressing II CSE 351 Spring

Summer May 18, 2010

CS2351 Data Structures. Lecture 7: A Brief Review of Pointers in C

Arrays and Pointers. Overview. Arrays Introducing Pointers C-Style Character Strings Multidimensioned Arrays

Arrays. Returning arrays Pointers Dynamic arrays Smart pointers Vectors

Computer Programming: C++

C++ Programming Chapter 7 Pointers

EL6483: Brief Overview of C Programming Language

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

Review! * follows a pointer to its value! & gets the address of a variable! Pearce, Summer 2010 UCB! ! int x = 1000; Pearce, Summer 2010 UCB!

CS61C : Machine Structures

Intermediate Programming, Spring 2017*

Today s lecture. Continue exploring C-strings. Pointer mechanics. C arrays. Under the hood: sequence of chars w/ terminating null

CS 107 Lecture 5: Arrays. and Pointers in C. Monday, January 22, Stanford University. Computer Science Department

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

Computer Science & Engineering 150A Problem Solving Using Computers

Memory, Arrays & Pointers

Pointers, Dynamic Data, and Reference Types

Arrays. Lecture 9 COP 3014 Fall October 16, 2017

by Pearson Education, Inc. All Rights Reserved.

Fundamentals of Programming Session 20

Lab 3. Pointers Programming Lab (Using C) XU Silei

CS 222: Pointers and Manual Memory Management

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

Fast Introduction to Object Oriented Programming and C++

Introduction. Programming in C++ Pointers and arrays. Pointers in C and C++ Session 5 - Pointers and Arrays Iterators

Arrays. Example: Run the below program, it will crash in Windows (TurboC Compiler)

Lecture 5: Outline. I. Multi- dimensional arrays II. Multi- level arrays III. Structures IV. Data alignment V. Linked Lists

C++ For Science and Engineering Lecture 15

CS 61c: Great Ideas in Computer Architecture

Lecture 8: Pointer Arithmetic (review) Endianness Functions and pointers

QUIZ. What are 3 differences between C and C++ const variables?

Advanced Systems Programming

EL2310 Scientific Programming

Heap Arrays and Linked Lists. Steven R. Bagley

Comp 11 Lectures. Mike Shah. June 26, Tufts University. Mike Shah (Tufts University) Comp 11 Lectures June 26, / 57

Programming. Pointers, Multi-dimensional Arrays and Memory Management

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

Appendix. Grammar. A.1 Introduction. A.2 Keywords. There is no worse danger for a teacher than to teach words instead of things.

C The new standard

A complex expression to evaluate we need to reduce it to a series of simple expressions. E.g * 7 =>2+ 35 => 37. E.g.

A brief introduction to C programming for Java programmers

CS31 Discussion. Jie(Jay) Wang Week8 Nov.18

I m sure you have been annoyed at least once by having to type out types like this:

CS61C : Machine Structures

CS201- Introduction to Programming Current Quizzes

POINTER AND ARRAY SUNU WIBIRAMA

Template Issue Resolutions from the Stockholm Meeting

Templating functions. Comp Sci 1570 Introduction to C++ Administrative notes. Review. Templates. Compiler processing. Functions Overloading

Tokens, Expressions and Control Structures

Review of Important Topics in CS1600. Functions Arrays C-strings

C++ ARRAYS POINTERS POINTER ARITHMETIC. Problem Solving with Computers-I

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #33 Pointer Arithmetic

More about BOOLEAN issues

[0569] p 0318 garbage

CprE 288 Introduction to Embedded Systems Exam 1 Review. 1

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

CS 220: Introduction to Parallel Computing. Arrays. Lecture 4

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

Introduction to Programming Using Java (98-388)

C & Data Structures syllabus

Learning Objectives. Introduction to Arrays. Arrays in Functions. Programming with Arrays. Multidimensional Arrays

REFERENCES, POINTERS AND STRUCTS

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #34. Function with pointer Argument

HW1 due Monday by 9:30am Assignment online, submission details to come

CS61C : Machine Structures

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.

Transcription:

Passing arrays to functions A big topic for beginners is how to write a function that can be passed an array. A very common way of achieving this is done using pointers. This method can be seen all through the C core in functions like memcpy(). Another way, which is the more natural choice for C++, but not as popular with beginners and C programmers is to pass the variable as an actual array. Both methods have their advantages, however each has their drawbacks. How you need to use the array in your own code should determine which is best. Pass an array using a pointer Pass a multidimensional array using pointer Pass an array using array types (single & multidimensional) Pass an array using a pointer An arrays name in code, without subscript operators [], is implicitly convertible to a pointer of its first element. An example of this is shown below. The pointer to arr[0] is assigned to the variable ptr. Contrary to popular belief, this is not a pointer to the array, and the array has implicitly been cast to a pointer, which is commonly referred to as decayed pointer, as it has been stripped of the information an array type provides. The example also shows how you can explicitly get the pointer of any array element. char arr[] = { 1, 2, 3, 4, 5 ; char *ptr = arr; //Or the equivalent ( change index to start mid-array ): char *ptr2 = &arr[0]; Once we have a pointer to an element, you can also use pointer arithmetic to navigate the array. When passing an array to a function using pointers, you can convert it to a pointer using the two methods explained above. The next example shows this basic principle in the function setup(): #define MAX_LEN 5 char arr[ MAX_LEN ] = { 1, 2, 3, 4, 5 ; void Func( char *ptr ){ for( int idx = MAX_LEN - 1 ; idx >= 0 ; --idx ){ Serial.println( ptr[ idx ], HEX ); Page 1 / 5

void setup(){ void loop() { The above setup works, however the function is limited in the fact it can not be reused easily. To make the code more generic and increase its reuseability, we can remove the hard coded length and pass it through the function also. char arr[] = { 1, 2, 3, 4, 5 ; void Func( char *ptr, int length ){ while( length ){ Serial.println( ptr[ --length ], HEX ); void setup(){ Func( arr, 5 ); Serial.println( "----------------" ); Func( &arr[2], 3 ); void loop() { Now the function allows arrays of any length you want. This method is almost always required to deal with an array of unknown size as the typical methods of retrieving the length of an array do not work with the pointer. Pass a multidimensional array using pointer The above example is a common and accepted way of dealing with array data. However this method is not as straight forward when using multidimensional arrays, for example, two dimensional array types do not convert to a 2D pointer (something like char **ptr). To pass a multidimensional array you must know the value of all dimensions except the first, so things become a little more restrictive. This short example shows how a multidimensional array can be passed. The functions Func() & Func2() are two different styles used to pass a multidimensional array, and just like the examples above you can add in extra parameters to tell the function the length of each Page 2 / 5

dimension: void Func( char array[][3] ){ return; void Func2( char (*array)[3] ){ return; void setup() { char arr[][3] = { { 0, 1, 2, { 3, 4, 5, { 6, 7, 8 ; Func2( arr ); void loop() { As you can see, with each extra dimension, the functions accepting the pointer become less and less generic and more specific to a particular array. This is where templates could be used to gain a more generic interface. However templates can provide many more capabilities and these are explained in the next section below. (adsbygoogle = window.adsbygoogle []).push({); Pass an array using array types Rather than having an array decay to a pointer every time you need to use it, you can utilize a reference object. themselves are types, which means we can create pointers and references to them just like any other type. The syntax becomes a little obscure due to the nature of the array declaration, however it allows for a different style of programming to the pointer methods in the section above. For example, we cannot simply add an & symbol to mark the array as a reference like: char &array[5] as this declares an array of references, which is illegal, and not what we want (a reference to an array). The & needs to be inside brackets to show its part of the array variable, and not the array data type: char (&array)[5]. In the following example, a function taking a reference to an array can replace the first two examples in the pointer method above: void Func( char (&array)[5] ){ for( int idx = 0 ; idx < sizeof( array ) ; ++idx ){ Serial.println( array[ idx ], HEX ); Page 3 / 5

void setup() { char arr[] = { 1,2,3,4,5 ; void loop(){ If you haven't already noticed, the function does not need the length to be passed in as sizeof will work correctly with a reference. The same function can be rewritten using an actual pointer to array, the only difference is the need to dereference the pointer back to an array before using it: void Func( char (*array)[5] ){ for( int idx = 0 ; idx < sizeof( *array ) ; ++idx ){ Serial.println( (*array)[ idx ], HEX ); //... char arr[] = { 1,2,3,4,5 ; Func( &arr ); //Pass the 'address of' the array. These examples, while useful, are still bound to an array of a certain length and are not quite as flexible as one may need. To write a function which will accept any size array, we can start to adopt some template features. The first change we can make is to let the compiler deduce the length of the array, so we can write one piece of code for any sized array (single dimension). template< size_t N > void Func( char (&array)[n] ){ for( int idx = 0 ; idx < N ; ++idx ){ Serial.println( array[ idx ], HEX ); The template parameter N will be replaced with a usable value when called with an array. And in the declaration we can replace the hard coded value with N. As this value is accessible as a Page 4 / 5

Powered by TCPDF (www.tcpdf.org) constant within the function, it also eliminates the need for sizeof. The next modification we can add is to allow arrays of any data type to use the function. This requires an additional template parameter, which we can use to replace the array type char: template< typename T, size_t N > void Func( T (&array)[n] ){ //code here To write a version of this function for multidimensional arrays we can simply add a new template parameter for each dimension: template< typename T, size_t N, size_t X > void Func( T (&array)[n][x] ){ //Code here template< typename T, size_t N, size_t X, size_t Y > void Func( T (&array)[n][x][y] ){ //Code here The benefit is each dimension is known and can be easily iterated. Heavy use of template style functions with different sized arrays could lead to code bloat, so these functions could be used as wrappers for pointer style functions, or to map multidimensional arrays onto functions accepting single dimension, which can be optimized very well by the compiler. Unique solution ID: #1031 Author: Christopher Andrews Last update: 2014-10-26 06:02 Page 5 / 5