Pointers: Parameter Passing and Return

Similar documents
ASCII Encoding. The char Type. Manipulating Characters. Manipulating Characters

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

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

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

Introduction to Programming II Winter, 2014 Assignment 2

Chapter 13 Storage classes

1 Abstract Data Types Information Hiding

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

Passing 1D arrays to functions.

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

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

System Calls Related to File Manipulation

Module 816. File Management in C. M. Campbell 1993 Deakin University

Comp151. Definitions & Declarations

Variables, Constants, and Data Types

The C Programming Language course syllabus associate level

C Strings and Pointers

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

Informatica e Sistemi in Tempo Reale

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

System Calls and Standard I/O

MATLAB: Strings and File IO

An Incomplete C++ Primer. University of Wyoming MA 5310

C Interview Questions

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)

CS 241 Data Organization Coding Standards

C++ Programming Language

5 Arrays and Pointers

Software security. Buffer overflow attacks SQL injections. Lecture 11 EIT060 Computer Security

C++ INTERVIEW QUESTIONS

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

Lecture 22: C Programming 4 Embedded Systems

File Handling. What is a file?

Scoping (Readings 7.1,7.4,7.6) Parameter passing methods (7.5) Building symbol tables (7.6)

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

Programming languages C

EXEC SQL CONNECT :userid IDENTIFIED BY :passwd;

C PROGRAMMING FOR MATHEMATICAL COMPUTING

Fondamenti di C++ - Cay Horstmann 1

Illustration 1: Diagram of program function and data flow

Answers to Review Questions Chapter 7

The Payroll Program. Payroll

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

Lecture 5: Java Fundamentals III

Tutorial on C Language Programming

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

Basics of I/O Streams and File I/O

An Introduction to Assembly Programming with the ARM 32-bit Processor Family

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

Number Representation

B.Sc.(Computer Science) and. B.Sc.(IT) Effective From July 2011

Basic Java Constructs and Data Types Nuts and Bolts. Looking into Specific Differences and Enhancements in Java compared to C

Semantic Analysis: Types and Type Checking

The programming language C. sws1 1

PROGRAMMING IN C PROGRAMMING IN C CONTENT AT A GLANCE

A single register, called the accumulator, stores the. operand before the operation, and stores the result. Add y # add y from memory to the acc

Stacks. Linear data structures

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

Unit Write iterative and recursive C functions to find the greatest common divisor of two integers. [6]

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

C++ Outline. cout << "Enter two integers: "; int x, y; cin >> x >> y; cout << "The sum is: " << x + y << \n ;

CS 106 Introduction to Computer Science I

How To Write Portable Programs In C

Simple C Programs. Goals for this Lecture. Help you learn about:

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

Data Structures using OOP C++ Lecture 1

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

Moving from CS 61A Scheme to CS 61B Java

ECE 341 Coding Standard

El Dorado Union High School District Educational Services

/* File: blkcopy.c. size_t n

Chapter 5 Names, Bindings, Type Checking, and Scopes

J a v a Quiz (Unit 3, Test 0 Practice)

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

Parameter Passing. Parameter Passing. Parameter Passing Modes in Fortran. Parameter Passing Modes in C

COMPUTER SCIENCE 1999 (Delhi Board)

Chapter 13 - The Preprocessor

C Dynamic Data Structures. University of Texas at Austin CS310H - Computer Organization Spring 2010 Don Fussell

University of Hull Department of Computer Science. Wrestling with Python Week 01 Playing with Python

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

We will learn the Python programming language. Why? Because it is easy to learn and many people write programs in Python so we can share.

Output: struct treenode{ int data; struct treenode *left, *right; } struct treenode *tree_ptr;

IPC. Semaphores were chosen for synchronisation (out of several options).

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

MPLAB TM C30 Managed PSV Pointers. Beta support included with MPLAB C30 V3.00

So far we have considered only numeric processing, i.e. processing of numeric data represented

Computer Systems II. Unix system calls. fork( ) wait( ) exit( ) How To Create New Processes? Creating and Executing Processes

2 ASCII TABLE (DOS) 3 ASCII TABLE (Window)

64-Bit NASM Notes. Invoking 64-Bit NASM

Computer Programming Tutorial

public static void main(string[] args) { System.out.println("hello, world"); } }

6.s096. Introduction to C and C++

CSC230 Getting Starting in C. Tyler Bletsch

Object Oriented Software Design II

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

8.5. <summary> Cppcheck addons Using Cppcheck addons Where to find some Cppcheck addons

7th Marathon of Parallel Programming WSCAD-SSC/SBAC-PAD-2012

CryptoAPI. Labs. Daniil Leksin

Transcription:

Pointers: Parameter Passing and Return 1

Passing Pointers to a Function Pointers are often passed to a function as arguments Allows data items within the calling function to be accessed by the called function, altered, and then returned to the calling function in altered form Useful for returning more than one value from a function Still call-by-value, but now the address is copied, not the content 2

Example: Swapping int main() int a, b; a = 5; b = 20; swap (a, b); printf ( \n a=%d, b=%d, a, b); return 0; void swap (int x, int y) int t; t = x; x = y; y = t; Output a=5, b=20 Parameters passed by value, so changes done on copy, not returned to calling function 3

Example: Swapping using pointers int main() int a, b; a = 5; b = 20; swap (&a, &b); printf ( \n a=%d, b=%d, a, b); return 0; void swap (int *x, int *y) int t; t = *x; *x = *y; *y = t; Output a=20, b=5 Parameters passed by address, changes done on the value stored at that address 4

While passing a parameter to a function, when should you pass its address instead of the value? Pass address if both these conditions are satisfied The parameter value will be modified inside the function body The modified value is needed in the calling function after the called function returns Consider the swap function to see this 5

Passing Arrays as Pointers Both the forms below are fine in the function body, as arrays are passed by passing the address of the first element. Calling function calls it the same way int main() int n; float list[100], avg; : avg = average (n, list); : int main() int n; float list[100], avg; : avg = average (n, list); : float average (int a, float x[]) : sum = sum + x[i]; float average (int a, float *x) : sum = sum + x[i]; 6

Returning multiple values from a function Return statement can return only one value What if we want to return more than one value? Use pointers Return one value as usual with a return statement For other return values, pass the address of a variable in which the value is to be returned 7

Example: Returning max and min of an array Both returned through pointers (could have returned one of them through return value of the function also) int main() int n, min, max, i, A[100]; scanf( %d, &n); for (i=0; i<n; ++i) scanf( %d, &A[i]); MinMax(A, n, &min, &max); printf( Min and max are %d, %d, min, max); return 0; void MinMax(int A[], int n, int *min, int *max) int i, x, y; x = y = A[0]; for (i=1; i<n; ++i) if (A[i] < x) x = A[i]; if (A[i] > y) y = A[i]; *min = x; *max = y; 8

Example: Passing structure pointers struct complex ; float re; float im; int main() struct complex a, b, c; scanf( %f%f, &a.re, &a.im); scanf( %f%f, &b.re, &b.im); add(&a, &b, &c) ; printf( \n %f %f, c.re, c.im); return 0; void add (struct complex *x, struct complex *y, struct complex *t) t->re = x->re + y->re; t->im = x->im + y->im; 9

Strings 10

Strings 1-d arrays of type char By convention, a string in C is terminated by the end-of-string sentinel \0 (null character) char s[21] - can have variable length string delimited with \0 Max length of the string that can be stored is 20 as the size must include storage needed for the \0 String constants : hello, abc abc is a character array of size 4 11

String Constant A string constant is treated as a pointer Its value is the base address of the string char *p = abc ; p a b c \0 printf ( %s %s\n,p,p+1); /* abc bc is printed */ 12

Differences : array & pointers char *p = abcde ; The compiler allocates space for p, puts the string constant abcde in memory somewhere else, initializes p with the base address of the string constant char s[ ] = abcde ; char s[ ] = a, b, c, d, e. \0 ; The compiler allocates 6 bytes of memory for the array s which are initialized with the 6 characters p a b c d e \0 S a b c d e \0 13

Library Functions for String Handling You can write your own C code to do different operations on strings like finding the length of a string, copying one string to another, appending one string to the end of another etc. C library provides standard functions for these that you can call, so no need to write your own code To use them, you must do #include <string.h> At the beginning of your program (after #include <stdio.h>) 14

String functions we will see strlen : finds the length of a string strcat : concatenates one string at the end of another strcmp : compares two strings lexicographically strcpy : copies one string to another 15

strlen() int strlen(const char *s) Takes a null-terminated strings (we routinely refer to the char pointer that points to a null-terminated char array as a string) Returns the length of the string, not counting the null (\0) character You cannot change contents of s in the function int strlen (const char *s) int n; for (n=0; *s!= \0 ; ++s) ++n; return n; 16

strcat() char *strcat (char *s1, const char *s2); Takes 2 strings as arguments, concatenates them, and puts the result in s1. Returns s1. Programmer must ensure that s1 points to enough space to hold the result. You cannot change contents of s2 in the function char *strcat(char *s1, const char *s2) char *p = s1; while (*p!= \0 ) /* go to end */ ++p; while(*s2!= \0 ) *p++ = *s2++; /* copy */ *p = \0 ; return s1; 17

Dissection of the strcat() function char *p = s1; p is being initialized, not *p. The pointer p is initialized to the pointer value s1. Thus p and s1 point to the same memory location 18

Dissection of the strcat() function char *p = s1; p is being initialized, not *p. The pointer p is initialized to the pointer value s1. Thus p and s1 point to the same memory location while (*p!= \0 ) ++p; As long as the value pointed to by p is not \0, p is incremented, causing it to point at the next character in the string. When p points to \0, the control exits the while statement 19

Dissection of the strcat() function char *p = s1; p is being initialized, not *p. The pointer p is initialized to the pointer value s1. Thus p and s1 point to the same memory location while (*p!= \0 ) ++p; As long as the value pointed to by p is not \0, p is incremented, causing it to point at the next character in the string. When p points to \0, the control exits the while statement while(*s2!= \0 ) *p++ = *s2++; /* copy */ At the beginning, p points to the null character at the end of string s1. The characters in s2 get copied one after another until end of s2 20

Dissection of the strcat() function char *p = s1; p is being initialized, not *p. The pointer p is initialized to the pointer value s1. Thus p and s1 point to the same memory location while (*p!= \0 ) ++p; As long as the value pointed to by p is not \0, p is incremented, causing it to point at the next character in the string. When p points to \0, the control exits the while statement while(*s2!= \0 ) *p++ = *s2++; /* copy */ At the beginning, p points to the null character at the end of string s1. The characters in s2 get copied one after another until end of s2 *p = \0 ; put the \0 at the end of the string 21

strcmp() int strcmp (const char *s1, const char *s2); Two strings are passed as arguments. An integer is returned that is less than, equal to, or greater than 0, depending on whether s1 is lexicographically less than, equal to, or greater than s2. 22

strcmp() int strcmp (const char *s1, const char *s2); Two strings are passed as arguments. An integer is returned that is less than, equal to, or greater than 0, depending on whether s1 is lexicographically less than, equal to, or greater than s2. int strcmp(char *s1, const char *s2) for (;*s1!= \0 &&*s2!= \0 ; s1++,s2++) if (*s1>*s2) return 1; if (*s2>*s1) return -1; if (*s1!= \0 ) return 1; if (*s2!= \0 ) return -1; return 0; 23

strcpy() char *strcpy (char *s1, char *s2); The characters is the string s2 are copied into s1 until \0 is moved. Whatever exists in s1 is overwritten. It is assumed that s1 has enough space to hold the result. The pointer s1 is returned. 24

strcpy() char *strcpy (char *s1, const char *s2); The characters is the string s2 are copied into s1 until \0 is moved. Whatever exists in s1 is overwritten. It is assumed that s1 has enough space to hold the result. The pointer s1 is returned. char * strcpy (char *s1, const char *s2) char *p = s1; while (*p++ = *s2++) ; return s1; 25

Example: Using string functions int main() char s1[ ] = "beautiful big sky country", s2[ ] = "how now brown cow"; printf("%d\n",strlen (s1)); printf("%d\n",strlen (s2+8)); printf("%d\n", strcmp(s1,s2)); printf("%s\n",s1+10); strcpy(s1+10,s2+8); strcat(s1,"s!"); printf("%s\n", s1); return 0; Output 25 9-1 big sky country beautiful brown cows! 26