英格兰萨里大学:《C语言》课程教学资源(讲义)Lecture 13 - More functions

BhirSOLecture 13UsingPointerswithfunctionsHghLSandardirpt ard otpt.LasttimewesawhowtousefunctionswithQperasimpledatatypes.Wecanalsousepointers,theapproachissimilarLapingchar* tail(char* s, char c);e.g.ientera.Thistakes a string s, looks for char cwithin it andbattrdreturns a string starting at that pointFleDta Sncre14CasesidyloteytergmeatoOPOyT RY?Weve already seen.tescoaygo tes eraetA.ta1mathat arrays are reallytatlpointers (lecture 9)pune.So we can use a[] - (2, 4-*)similar approach with*Tthemol.P0TheseprogramsP甲PS411.0tillustratethe case.epwhere the array sizeap e.is fixed. Later wellwhe.see how to generalise国lpp14the functions for114)国富1variable size arraysaecall-by-value,call-by-referencecall-by-value,call-by-reference.Therearetwobasicwaysofpassingarguments·AnalogiestofunctionsCallowsboth- call-by-value.call-by-value· is like taking a photocopy ofa document andthe values of the function arguments are copied to the functionsgiving it to someone. If they change it, theintemal parameters. If thecopy is changed,thevalueoftheoriginal is unaffected.original argument is not affected.-call-by-referencecall-by-reference? is like giving someone access to the original-the address oftheoriginal variables arepassed tothe functiondocumentas pointer arguments. The addresses are copied to the functionsintemal (pointer)parameters.This thefunction hasfullaccesstothe original variables and can change them
1 1. Introduction 2. Binary Representation 3. Hardware and Software 4. High Level Languages 5. Standard input and output 6. Operators, expression and statements 7. Making Decisions 8. Looping 9. Arrays 10. Basics of pointers 11. Strings 12. Basics of functions 13. More about functions 14. Files 14. Data Structures 16. Case study: lottery number generator Lecture 13 Lecture 13 Using Pointers with functions • Last time we saw how to use functions with simple data types • We can also use pointers, the approach is similar e.g. char* tail(char* s, char c); • This takes a string s, looks for char c within it and returns a string starting at that point returns a pointer-to-char identifier argument pointer-to-char argument char /* Example: pointer as return value of functions */ /* Often used with arrays and strings */ #include char *tail(char *s, char c); /* returns tail of s, from c on */ main() { char str[] = "Introduction to Programming and \ Computer Architecture"; /* strings may be wrapped using '\' */ char ch, *p; puts("Enter a character:"); ch = getchar(); p = tail(str, ch); if (p == NULL) puts("Not present in string."); else puts(p); } char *tail(char *s, char c) /* returns tail of s, from c on */ { char *t = s; do /* scan along s until c or '\0' is found */ { if (*t == c) return t; } while (*(t++) != '\0'); return NULL; /* reached end of s, c not found. NULL is an appropriate pointer value to signal an error */ } /* Example: pointer as return value of functions */ /* Often used with arrays and strings */ #include char *tail(char *s, char c); /* returns tail of s, from c on */ main() { char str[] = "Introduction to Programming and \ Computer Architecture"; /* strings may be wrapped using '\' */ char ch, *p; puts("Enter a character:"); ch = getchar(); p = tail(str, ch); if (p == NULL) puts("Not present in string."); else puts(p); } char *tail(char *s, char c) /* returns tail of s, from c on */ { char *t = s; do /* scan along s until c or '\0' is found */ { if (*t == c) return t; } while (*(t++) != '\0'); return NULL; /* reached end of s, c not found. NULL is an appropriate pointer value to signal an error */ } pointret.c pointret.c /* Example: passing arrays to functions */ #include #include void print_vec(int v[3]); /* Prints 3-vector v */ float length(int v[3]); /* Finds length of 3-vector v */ void main(void) { int a[3] = {2, 4, -6}; puts("vector a:"); print_vec(a); printf("length = %f\n", length(a)); return; } void print_vec(int v[3]) /* Prints 3-vector v */ { printf("[ %2i ", v[0]); printf("%2i ", v[1]); printf("%2i ]\n", v[2]); return; } float length(int v[3]) /* Finds length of 3-vector v */ { float len2 = 0; int i; for (i = 0; i #include void print_vec(int v[3]); /* Prints 3-vector v */ float length(int v[3]); /* Finds length of 3-vector v */ void main(void) { int a[3] = {2, 4, -6}; puts("vector a:"); print_vec(a); printf("length = %f\n", length(a)); return; } void print_vec(int v[3]) /* Prints 3-vector v */ { printf("[ %2i ", v[0]); printf("%2i ", v[1]); printf("%2i ]\n", v[2]); return; } float length(int v[3]) /* Finds length of 3-vector v */ { float len2 = 0; int i; for (i = 0; i < 3; i++) len2 += v[i] * v[i]; return sqrt(len2); } • Weve already seen that arrays are really pointers (lecture 9) • So we can use a similar approach with them • These programs illustrate the case where the array size is fixed. Later well see how to generalise the functions for variable size arrays call-by-value, call-by-reference • There are two basic ways of passing arguments to functions, C allows both • call-by-value – the values of the function arguments are copied to the functions internal parameters. If the copy is changed, the value of the original argument is not affected. • call-by-reference – the address of the original variables are passed to the function as pointer arguments. The addresses are copied to the functions internal (pointer) parameters. This the function has full access to the original variables and can change them call-by-value, call-by-reference • Analogies – call-by-value • is like taking a photocopy of a document and giving it to someone. If they change it, the original is unaffected. – call-by-reference • is like giving someone access to the original document

的岛+ AREnSB.SS.myodems联命出call-by-value,call-by-reference. When to use which?hput_FunctionarpynAn-*aTmopsnaATtoTBU-Forinputinputloutput? use call-by-value?--For output. if single value, use retun value.4.tA? if multiple values, use call-by-reference1-For input/output山通Ia) wxd? use call-by-referenceounA.However, with pointer arguments (strings, arrays)your using call-by-reference anywayScopeof VariablesScopeof Variables:Mostvariableswevedefinedwithinmain()The scope of a variable is the region of the..But theycan also bedefined in otherprogram where it is "visible"functions,insideblocks or even outsideall- Global variables are visible throughout thefunctions i.e.globalprogram*Globalvariables Local variables are visible only within the blockvariables declared at the start of the program,they were definedoutside all functions, are accessible to all functions.If a local variable is declared with the same- Within each function you can redeclare themidentifieras a global variable,it'masks"the:LocalVariablesglobalonei.e.theglobalbecomes variables declared within a function or block (),temporarily invisibleceaseto existaftertheblock is leftSredosglobal.cali前福teA *:性一-ani,emIPR-af-a1 ies Fan 1apoad eaung PIPTOe 1g T2
2 call-by-value, call-by-reference • When to use which? – For input • use call-by-value – For output • if single value, use return value • if multiple values, use call-by-reference – For input/output • use call-by-reference • However, with pointer arguments (strings, arrays) your using call-by-reference anyway Function input output input/output /* Example: function call by value and call by reference */ #include void swap1(int a, int b); /* doesn't work */ void swap2(int *p1, int *p2); /* works properly */ main() { int x = 5, y = 6; printf("Initially: x = %i, y = %i\n", x, y); swap1(x, y); /* call by value */ printf("After swap1: x = %i, y = %i\n", x, y); swap2(&x, &y); /* call by reference */ printf("After swap2: x = %i, y = %i\n", x, y); } /* Call by value: the function argument is of a simple data type. Its value is copied to the corresponding function parameter. The copy may be changed, but on return the argument is unaffected. Used for an "input-only" argument. */ void swap1(int a, int b) /* doesn't work */ { int temp; temp = a; /* this swaps the values of parameters a and b, */ a = b; /* but doesn't change the arguments x and y in main */ b = temp; return; } /* Call by reference: the function argument is a pointer (address of a variable). The function has full access to the "pointee", and can change its value. Used for an "input/output" or "output only" argument.*/ void swap2(int *p1, int *p2) /* works properly */ { int temp; temp = *p1; /* this swaps the values of "pointees" *p1 and *p2, */ *p1 = *p2; /* so changes x and y in main, as desired */ *p2 = temp; return; } /* Example: function call by value and call by reference */ #include void swap1(int a, int b); /* doesn't work */ void swap2(int *p1, int *p2); /* works properly */ main() { int x = 5, y = 6; printf("Initially: x = %i, y = %i\n", x, y); swap1(x, y); /* call by value */ printf("After swap1: x = %i, y = %i\n", x, y); swap2(&x, &y); /* call by reference */ printf("After swap2: x = %i, y = %i\n", x, y); } /* Call by value: the function argument is of a simple data type. Its value is copied to the corresponding function parameter. The copy may be changed, but on return the argument is unaffected. Used for an "input-only" argument. */ void swap1(int a, int b) /* doesn't work */ { int temp; temp = a; /* this swaps the values of parameters a and b, */ a = b; /* but doesn't change the arguments x and y in main */ b = temp; return; } /* Call by reference: the function argument is a pointer (address of a variable). The function has full access to the "pointee", and can change its value. Used for an "input/output" or "output only" argument.*/ void swap2(int *p1, int *p2) /* works properly */ { int temp; temp = *p1; /* this swaps the values of "pointees" *p1 and *p2, */ *p1 = *p2; /* so changes x and y in main, as desired */ *p2 = temp; return; } swap.c swap.c Scope of Variables • Most variables weve defined within main() • But they can also be defined in other functions, inside blocks or even outside all functions i.e. global • Global variables – variables declared at the start of the program, outside all functions, are accessible to all functions – Within each function you can redeclare them • Local Variables – variables declared within a function or block { }, cease to exist after the block is left Scope of Variables • The scope of a variable is the region of the program where it is “visible” – Global variables are visible throughout the program – Local variables are visible only within the block they were defined • If a local variable is declared with the same identifier as a global variable, it “masks” the global one i.e. the global becomes temporarily invisible. /* Example: global variables */ /* Like goto statements, global (external) variables may seem convenient, but experience shows they can cause many bugs. */ #include void func1(void); void func2(void); int g = 523; /* global variable, visible throughout this file */ void main(void) { extern int g; /* not actually necessary, but good practice */ printf("[main]: g = %3i\n", g); g = 7; printf("[main]: g = %3i\n", g); func1(); printf("[main]: g = %3i\n", g); return; } void func1(void) { extern int g; /* not actually necessary, but good practice */ g += 100; printf("[func1]: g = %3i\n", g); func2(); printf("[func1]: g = %3i\n", g); return; } void func2(void) { extern int g; /* not actually necessary, but good practice */ g *= 2; printf("[func2]: g = %3i\n", g); return; } /* Example: global variables */ /* Like goto statements, global (external) variables may seem convenient, but experience shows they can cause many bugs. */ #include void func1(void); void func2(void); int g = 523; /* global variable, visible throughout this file */ void main(void) { extern int g; /* not actually necessary, but good practice */ printf("[main]: g = %3i\n", g); g = 7; printf("[main]: g = %3i\n", g); func1(); printf("[main]: g = %3i\n", g); return; } void func1(void) { extern int g; /* not actually necessary, but good practice */ g += 100; printf("[func1]: g = %3i\n", g); func2(); printf("[func1]: g = %3i\n", g); return; } void func2(void) { extern int g; /* not actually necessary, but good practice */ g *= 2; printf("[func2]: g = %3i\n", g); return; } /* Example: local variable within a block */ #include #define R 47.0 /* resistance */ void main(void) { float i; /* current */ float v = 12.0; /* voltage */ i = v/R; /* Ohm's law */ printf("Current = %7.4f A\n", i); { int i; /* A new variable, local to this block */ for (i = 10; i >= 0; i-) printf("%i ", i); putchar('\n'); } printf("Current = %7.4f A\n", i); return; } /* Example: local variable within a block */ #include #define R 47.0 /* resistance */ void main(void) { float i; /* current */ float v = 12.0; /* voltage */ i = v/R; /* Ohm's law */ printf("Current = %7.4f A\n", i); { int i; /* A new variable, local to this block */ for (i = 10; i >= 0; i-) printf("%i ", i); putchar('\n'); } printf("Current = %7.4f A\n", i); return; } global.c global.c local.c local.c /* Example: scope of variables */ #include void func1(void); void func2(void); /* The scope of a variable is the block in which it is declared. External (global) variables, declared at the start of the program outside all blocks, are visible throughout the whole file. However, they are masked by any local variable declared with the same identifier. */ int a = 1; /* Global variables, visible throughout */ int b = 2; /* this file */ void main(void) { printf("[main]: a = %i, b = %i\n", a, b); func1(); func2(); printf("[main]: a = %i, b = %i\n", a, b); return; } void func1(void) { extern int a; /* The global "a" is visible here */ int b = 3; /* A new variable, local to func1 The global b is masked */ a++; printf("[func1]: a = %i, b = %i\n", a, b); return; /* local variable b is destroyed */ } void func2(void) { int a = 4; /* A new variable, local to func2 The global a is masked */ extern int b; /* The global "b" is visible here */ b++; printf("[func2]: a = %i, b = %i\n", a, b); return; /* local variable a is destroyed */ } /* Example: scope of variables */ #include void func1(void); void func2(void); /* The scope of a variable is the block in which it is declared. External (global) variables, declared at the start of the program outside all blocks, are visible throughout the whole file. However, they are masked by any local variable declared with the same identifier. */ int a = 1; /* Global variables, visible throughout */ int b = 2; /* this file */ void main(void) { printf("[main]: a = %i, b = %i\n", a, b); func1(); func2(); printf("[main]: a = %i, b = %i\n", a, b); return; } void func1(void) { extern int a; /* The global "a" is visible here */ int b = 3; /* A new variable, local to func1 The global b is masked */ a++; printf("[func1]: a = %i, b = %i\n", a, b); return; /* local variable b is destroyed */ } void func2(void) { int a = 4; /* A new variable, local to func2 The global a is masked */ extern int b; /* The global "b" is visible here */ b++; printf("[func2]: a = %i, b = %i\n", a, b); return; /* local variable a is destroyed */ } scope.c scope.c [main]: a = 1, b = 2 [func1]: a = 2, b = 3 [func2]: a = 4, b = 3 [main]: a = 2, b = 3 [main]: a = 1, b = 2 [func1]: a = 2, b = 3 [func2]: a = 4, b = 3 [main]: a = 2, b = 3

StaticLocal Variablesmain()asafunction.Mainisafunctiontoo.Itcanaccept:If a local variable isargumentsfortheoperating systemdeclared using theshell and canreturna valuetotheshellstatic keyword, itsvalue is preserved:It can be declared aswhen the block is leftArgument vectormain()(array of strings), theand reinstantiatedvoid main (void)_arguments trom the shellwhen the block is re-Snt main(void)Ent main(int arge, chary argvl1)enteredReturis an int to theThe oppositetothis isArgument countshell(eg unix csh)auto which is rarelyN of arguments passedAE!usedNote that argv[oj is always present and contains the..nameoftheprogramsoargc>=1Exitingprograms.The normal return value is zero, but it isnain.cbetter to #includeand return thevalueEXIT_SUCCESS(orEXIT_FAILUREisaproblemoccurs)Itisalsopossibletoabortaprogramfrom.within a function using exit(EXIT_FAILURE);Values retumed tothe shellaretypically usedby shell scripts.Beyond the scope ofthiscourseexit.c3
3 Static Local Variables • If a local variable is declared using the static keyword, its value is preserved when the block is left and reinstantiated when the block is reentered • The opposite to this is auto which is rarely used /* Example: static local variables within a function */ #include void add_one(void); void main(void) { int p; for (p = 0; p void add_one(void); void main(void) { int p; for (p = 0; p =1 Returns an int to the shell (eg unix csh) Argument count N’ of arguments passed Argument vector (array of strings), the arguments from the shell D:\a.out these are the command line arguments you can enter when you run the program The name of this program is a.out Argument #1 is these Argument #2 is are Argument #3 is the Argument #4 is command Argument #5 is line Argument #6 is arguments Argument #7 is you Argument #8 is can Argument #9 is enter Argument #10 is when Argument #11 is you Argument #12 is run Argument #13 is the Argument #14 is program D:\ D:\a.out these are the command line arguments you can enter when you run the program The name of this program is a.out Argument #1 is these Argument #2 is are Argument #3 is the Argument #4 is command Argument #5 is line Argument #6 is arguments Argument #7 is you Argument #8 is can Argument #9 is enter Argument #10 is when Argument #11 is you Argument #12 is run Argument #13 is the Argument #14 is program D:\ /* Example: main as a function */ /* Shows use of argc and argv[] and return value */ /* You can feed arguments from the operating system shell to main. At the Unix prompt, try entering: a.out 3 blind mice */ #include #include int main(int argc, char *argv[]) { /* argc argument count: number of arguments given */ /* argv[] argument vector: array of argument strings */ int i; /* argv[0], the program's name, is always present */ printf("The name of this program is %s\n", argv[0]); for (i = 1; i */ } /* Example: main as a function */ /* Shows use of argc and argv[] and return value */ /* You can feed arguments from the operating system shell to main. At the Unix prompt, try entering: a.out 3 blind mice */ #include #include int main(int argc, char *argv[]) { /* argc argument count: number of arguments given */ /* argv[] argument vector: array of argument strings */ int i; /* argv[0], the program's name, is always present */ printf("The name of this program is %s\n", argv[0]); for (i = 1; i */ } main.c main.c Exiting programs • The normal return value is zero, but it is better to #include and return the value EXIT_SUCCESS (or EXIT_FAILURE is a problem occurs) • It is also possible to abort a program from within a function using exit(EXIT_FAILURE); • Values returned to the shell are typically used by shell scripts. Beyond the scope of this course /* Example: aborting a program in an emergency, using exit */ #include #include int quotient(int numer, int denom); int main(void) { int a, b, c; for (b = 5; b > -5; b-) for (a = 20; a > 0; a -= 5) { c = quotient(a, b); printf("%i/%i = %i\n", a, b, c); } return EXIT_SUCCESS; } int quotient(int numerator, int denominator) { if (denominator == 0) { puts("Error [quotient]: attempted division by zero"); exit(EXIT_FAILURE); /* value returned to the shell */ } else return numerator/denominator; } /* Example: aborting a program in an emergency, using exit */ #include #include int quotient(int numer, int denom); int main(void) { int a, b, c; for (b = 5; b > -5; b-) for (a = 20; a > 0; a -= 5) { c = quotient(a, b); printf("%i/%i = %i\n", a, b, c); } return EXIT_SUCCESS; } int quotient(int numerator, int denominator) { if (denominator == 0) { puts("Error [quotient]: attempted division by zero"); exit(EXIT_FAILURE); /* value returned to the shell */ } else return numerator/denominator; } exit.c exit.c
按次数下载不扣除下载券;
注册用户24小时内重复下载只扣除一次;
顺序:VIP每日次数-->可用次数-->下载券;
- 英格兰萨里大学:《C语言》课程教学资源(讲义)Lecture 12 - Basics of Functions.pdf
- 英格兰萨里大学:《C语言》课程教学资源(讲义)Lecture 11 - Strings.pdf
- 英格兰萨里大学:《C语言》课程教学资源(讲义)Lecture 10 - Basics of Pointers.pdf
- 英格兰萨里大学:《C语言》课程教学资源(讲义)Lecture 9 - Arrays.pdf
- 英格兰萨里大学:《C语言》课程教学资源(讲义)Lecture 3 - Hardware and Software.pdf
- 英格兰萨里大学:《C语言》课程教学资源(讲义)Lecture 8 - Looping.pdf
- 英格兰萨里大学:《C语言》课程教学资源(讲义)Lecture 7 - Making Decisions.pdf
- 英格兰萨里大学:《C语言》课程教学资源(讲义)Lecture 6 - Operators, Expressions and Statements.pdf
- 英格兰萨里大学:《C语言》课程教学资源(讲义)Lecture 5 - Standard IO.pdf
- 英格兰萨里大学:《C语言》课程教学资源(讲义)Lecture 4 - Simple Data Types.pdf
- 英格兰萨里大学:《C语言》课程教学资源(讲义)Lecture 2 - Binary Representation.pdf
- 英格兰萨里大学:《C语言》课程教学资源(讲义)Lecture 1 - Introduction.pdf
- 《计算机程序设计基础》课程学习指南(C语言)给C语言初学者的学习建议.pdf
- 《计算机程序设计基础》课程学习指南(C语言)C语言初学者编程规范-2/2.pdf
- 《计算机程序设计基础》课程学习指南(C语言)C语言初学者编程规范-1/2.pdf
- 《计算机程序设计基础》课程学习指南(C语言)C语言常见问题详解.pdf
- 《计算机程序设计基础》课程学习指南(C语言)C语言常见英文单词.pdf
- 《计算机程序设计基础》课程学习指南(C语言)C语言常见错误中英文对照表.pdf
- 《计算机程序设计基础》课程教学大纲 C Programming Language(C语言).pdf
- 《计算机控制系统》课程教学资源(PPT课件)第7章 计算机控制系统设计与实现.ppt
- 英格兰萨里大学:《C语言》课程教学资源(讲义)Lecture 14 - Files.pdf
- 英格兰萨里大学:《C语言》课程教学资源(讲义)Lecture 15 - Data Structures.pdf
- 《计算机程序设计基础》课程授课教案(C语言)第1章 C语言概述.pdf
- 《计算机程序设计基础》课程授课教案(C语言)第2章 基本数据类型和运算符.pdf
- 《计算机程序设计基础》课程授课教案(C语言)第3章 控制结构.pdf
- 《计算机程序设计基础》课程授课教案(C语言)第4章 数组和指针.pdf
- 《计算机程序设计基础》课程授课教案(C语言)第5章 模块化编程.pdf
- 《计算机程序设计基础》课程授课教案(C语言)第6章 指针进阶与内存空间管理.pdf
- 《计算机程序设计基础》课程授课教案(C语言)第7章 结构体与共同体.pdf
- 《计算机程序设计基础》课程授课教案(C语言)第8章 数据文件编程方法.pdf
- 《计算机程序设计基础》课程PPT教学课件(C语言)第1章 C语言概述 1-10 IO函数值和注释语句.ppt
- 《计算机程序设计基础》课程PPT教学课件(C语言)第1章 C语言概述 1-8 标识符和关键字.ppt
- 《计算机程序设计基础》课程PPT教学课件(C语言)第1章 C语言概述 1-11 编程风格与常见错误.ppt
- 《计算机程序设计基础》课程PPT教学课件(C语言)第1章 C语言概述 1-9 输入输出函数.ppt
- 《计算机程序设计基础》课程PPT教学课件(C语言)第1章 C语言概述 1-7 实例求圆柱体底面积和体积.ppt
- 《计算机程序设计基础》课程PPT教学课件(C语言)第1章 C语言概述 1-5 第1个C程序解析.ppt
- 《计算机程序设计基础》课程PPT教学课件(C语言)第1章 C语言概述 1-6 预处理指令#define#include.ppt
- 《计算机程序设计基础》课程PPT教学课件(C语言)第1章 C语言概述 1-4 算法的表示.ppt
- 《计算机程序设计基础》课程PPT教学课件(C语言)第1章 C语言概述 1-1 C语言的概述.ppt
- 《计算机程序设计基础》课程PPT教学课件(C语言)第1章 C语言概述 1-2 结构化程序设计方法.ppt