0 Chap. 5 Pointers and Arrays 5.3Pointers and Arrays 5.4Address Arithmetic 5.5Character Pointers and Functions 5.6Pointer Arrays; Pointers to Pointers.

Slides:



Advertisements
Similar presentations
Programming Languages and Paradigms The C Programming Language.
Advertisements

Programming in C Pointers and Arrays, malloc( ). 7/28/092 Dynamic memory In Java, objects are created on the heap using reference variables and the new.
More Pointers Write a program that: –Calls a function to input an integer value –The above function calls another function that will double the input value.
Kernighan/Ritchie: Kelley/Pohl:
ECE 353: Lab C Pointers and Structs. Basics A pointer holds an address to some variable Notation: – Dereferencing operator: * int *x is a declaration.
CSSE 332 Functions, Pointers in C. 2 Functions - why and how ? If a problem is large If a problem is large Modularization – easier to: Modularization.
Pointers and dynamic objects COMP171 Fall Pointers and dynamic objects/ Slide 2 Topics * Pointers n Memory addresses n Declaration n Dereferencing.
C. About the Crash Course Cover sufficient C for simple programs: variables and statements control functions arrays and strings pointers Slides and captured.
What does this program do ? #include int main(int argc, char* argv[]) { int i; printf("%d arguments\n", argc); for(i = 0; i < argc; i++) printf(" %d: %s\n",
0 Chap. 5 Pointers and Arrays 5.1Pointers and Adresses 5.2Pointers and Function Arguments 5.3Pointers and Arrays 5.4Address Arithmetic 5.5Character Pointers.
Pointers and Arrays C and Data Structures Baojian Hua
1 CS 201 Array Debzani Deb. 2 Having trouble linking math.h? Link with the following option gcc –lm –o test test.o.
Exercise 10 Review: pointers, strings and recursion.
Chapter 8 Arrays and Strings
C arrays (Reek, Ch. 8) 1CS 3090: Safety Critical Programming in C.
Pointers. Why pointers? - low-level, but efficient manipulation of memory - dynamic objects  Objects whose memory is allocated during program execution.
Programming in C Pointers and Arrays. 1/14/102 Pointers and Arrays In C, there is a strong relationship between pointers and arrays.In C, there is a strong.
Arrays and Pointers in C Alan L. Cox
Arrays, Strings, and Pointers CSE 2451 Rong Shi. Arrays Store many values of the same type in adjacent memory locations Declaration [ ] Examples: – int.
Dale Roberts Department of Computer and Information Science, School of Science, IUPUI CSCI 230 Characters and Strings Literals and Variables Dale Roberts,
Pointers CSE 2451 Rong Shi.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 10. Pointers & Dynamic Data Structures.
Chapter Nine: Subprograms Lesson 09. What are they  Modularized code  Might return a value  Functions  Or not  Procedures  Subroutines  In object.
Chapter 8 Arrays and Strings
0 4.3 First Large Coding Example: calculator (kr76-79): Example of a Stack Machine Description of the problem and approach Pseudo code Flat implementation.
C++ Lecture 3 Monday, 14 July Arrays, Pointers, and Strings l Use of array in C++, multi- dimensional array, array argument passing l Pointers l.
Pointers. What is pointer l Everything stored in a computer program has a memory address. This is especially true of variables. char c=‘y’; int i=2; According.
1 6.1 Basics of Structures 6.2 Structures and Functions 6.3 Arrays of Structures 6.4 Pointers to Structures 6.5 Self-referential Structures + Linked List.
Lecture 22: Reviews for Exam 2. Functions Arrays Pointers Strings C Files.
1 Command-Line Processing In many operating systems, command-line options are allowed to input parameters to the program SomeProgram Param1 Param2 Param3.
Pointers A pointer is a variable that contains a memory address as it’s value. The memory address points to the actual data. –A pointer is an indirect.
Weeks 5-6 Pointers and Arrays Basic pointer type Pointers and Arrays Address arithmetic Pointer Arrays User-defined data types Structures Unions Pointers.
CSE 232: C++ memory management Overview of Arrays Arrays are the simplest kind of data structure –One item right after another in memory (“contiguous range”
C Programming Lecture 16 Pointers. Pointers b A pointer is simply a variable that, like other variables, provides a name for a location (address) in memory.
Fall 2004CS-183 Dr. Mark L. Hornick 1 C++ Arrays C++ (like Java) supports the concept of collections – mechanisms to sort and manipulate many instances.
Pointers in C++. Topics Covered  Introduction to Pointers  Pointers and arrays  Character Pointers, Arrays and Strings  Examples.
Arrays and Pointers.
Engineering Computing I Chapter 5 Pointers and Arrays.
Multi-dimensional Arrays and other Array Oddities Rudra Dutta CSC Spring 2007, Section 001.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 11: Pointers.
CPS120 Introduction to Computer Science Exam Review Lecture 18.
Arrays and Pointers (part 2) CSE 2031 Fall March 2016.
ADVANCED POINTERS. Overview Review on pointers and arrays Common troubles with pointers Multidimensional arrays Pointers as function arguments Functions.
Chapter 16 Pointers and Arrays Pointers and Arrays We've seen examples of both of these in our LC-3 programs; now we'll see them in C. Pointer Address.
Array and Pointers An Introduction Unit Unit Introduction This unit covers the usage of pointers and arrays in C++
CSE 332: C++ expressions Expressions: Operators and Operands Operators obey arity, associativity, and precedence int result = 2 * 3 + 5; // assigns 11.
Dale Roberts Department of Computer and Information Science, School of Science, IUPUI CSCI 230 Characters and Strings Dale Roberts, Lecturer Computer Science,
1 Homework Continue with K&R Chapter 5 –Skipping sections for now –Not covering section 5.12 Continue on HW5.
Chapter 5 Pointers and Arrays Ku-Yaw Chang Assistant Professor, Department of Computer Science and Information Engineering Da-Yeh.
Object Oriented Programming Lecture 2: BallWorld.
Windows Programming Lecture 03. Pointers and Arrays.
1 Memory, Arrays & Pointers. Memory 2 int main() { char c; int i,j; double x; cijx.
CSC 215 Pointers and Arrays. Pointers C provides two unary operators, & and *, for manipulating data using pointers The operator &, when applied to a.
C arrays (Reek, Ch. 8) CS 3090: Safety Critical Programming in C.
Functions Students should understand the concept and basic mechanics of the function call/return pattern from CS 1114/2114, but some will not. A function.
Chapter 5, Pointers and Arrays
Characters and Strings
Command Line Arguments
Pointers.
Arrays and Pointers CSE 2031 Fall September 2018.
Programming Languages and Paradigms
CS 240 – Lecture 18 Command-line Arguments, Typedef, Union, Bit Fields, Pointers to Functions.
Homework Continue with K&R Chapter 5 Skipping sections for now
Exercise Arrays.
Programming in C Pointers and Arrays.
Arrays and Pointers (part 2)
Arrays, Pointers, and Strings
ENERGY 211 / CME 211 Lecture 8 October 8, 2008.
Arrays and Pointers (part 2)
Characters and Strings
Presentation transcript:

0 Chap. 5 Pointers and Arrays 5.3Pointers and Arrays 5.4Address Arithmetic 5.5Character Pointers and Functions 5.6Pointer Arrays; Pointers to Pointers 5.7Multidimensional Arrays 5.8Initialization of Pointer Arrays 5.9Pointers vs Multi-dimensional Arrays 5.10Command-line Arguments: main(int argc, *argv[]) 5.11Pointers to Functions 5.12Complicated Declarations + Summary of Basic Declarations 6.7 typedef – first visit System-oriented Programming, B. Hirsbrunner, diuf.unifr.ch/pai/sp, Lecture 6 – 24 March 2015 kr5: Pointers and Arrays (~90') + exercises: ~90'

1 *** 5.3 Pointers and Arrays, 5.4 Address Arithmetic *** a The name of this array is “a” and its value is equivalent to the address of its first element: &a[0]. a+2 p+3 a+i points to the i-th element beyond a. p+i points to the i-th element beyond p. As p is a variable, p=a or ++p are legal; but as an array name is not a variable, expression like a=p or ++a are illegal ! p int *p=a; a[3] a[1] a[0] a[2] int a[4]; The declaration int a[4]; defines an array of size 4, that is, a block of 4 consecutive variables of type int, named a[0], a[1], a[2], a[3]. Tricky: p-a is legal, but not p+a ! Reminder: if p is a generic pointer, i.e. void *p, the only defined operation is the back and forth casting to any other type of pointers. come back to this slide if you are lost with pointers and arrays

2 5.5 Character Pointers and Functions Within the called function, this array name becomes a local pointer variable! When an array name a is passed to a function, what is passed is the address of a's first element, i.e. &a[0]. That means: as a formal parameter in a function definition, char a[] and char *p are equivalent : int f(char a[]); int f(char *p); and in both cases, the following calls will work: f(a); // char a[] = "hello"; f(p); // char *p = a; //same result as previous call f("hello"); // constant string ! //-–- crash if f's body write to a cell of the //––– constant string Let be the prototype: int f(char a[]); "Proof": next slide

3 in (1) 'a' is an immutable pointer to a mutable string in (2) 'p' is a mutable pointer to the same object as 'a' in (3) 'q' is a mutable pointer to a possibly immutable string in (7) "hello" is an immutable string A "Proof" : a test program and its function frames /* Return length of string s */ int strlen(char s[]) { int n; for (n = 0; *s != '\0'; s++) n++; return n; } void main() { (0) int i1, i2, i3, i4; (1) char a[] = "hello"; (2) char *p = a; (3) char *q = "hello"; (4) i1 = strlen(a); (5) i2 = strlen(p); (6) i3 = strlen(q); (7) i4 = strlen("hello"); } ‘o’‘o’ ‘l’‘l’ ‘l’‘l’ ’e' '\0' 'h' constant string (sdh segment) (7) strlen's frame (stack segment) (4), (5) s n strlen's frame (stack segment) (7) s n ‘o’‘o’ ‘l’‘l’ ‘l’‘l’ '\0' mutable string (sdh segment) (1), (2) ‘e’‘e’ 'h''h' ‘o’‘o’ ‘l’‘l’ ‘l’‘l’ ’e' '\0' 'h' possibly constant string (sdh segment) (3) strlen's frame (stack segment) (6) s n a: q p q i1 i3 i2 main's frame (stack segment) (0) - (3) i4 p sdh stands for stack, data or heap (it is up to the compiler or the runtime to decide)

4 5.6 Pointer Arrays; Pointers to Pointers Since pointers are variables themselves, they can be stored in arrays just as other variables can. Example: Design a program that will sort a set of text lines into alphabetic order. First Idea de\0 jk\0 abc\0 de\0 jk\0 abc\0 The sorting process has three steps Read all the lines of input Sort them Print them in order Complete solution See pp (will not be discussed in this course) Second Idea d e \0 j k \0 a b c \0 d e \0 j k \0 a b c \0

5 5.7 Multidimensional Arrays Initialization of Pointer Arrays Array definition char a[2]; // a is an array[2] of char, // i.e. a constant pointer to an array[2] of char char a[2][3]; // a is an array[2] of 'array[3] of char', // i.e. a matrix of 2 rows and 3 columns Array definition with initialization char a[2] = {'a','b'}; char a[2][3] = {{'a','b','c'}, {'d','e','f'}}; char a[2][3];

6 5.9 Pointers vs. Multi-dimensional Arrays Tricky char *ap[]; // ap is an array[] of pointer to char; char (*pa)[]; // pa is a pointer to an array[] of char; char aa[][8]; // aa is an array[] of array[8] of char; Two Examples

7 #include /* echo command-line arguments; 1st version */ int main(int argc, char *argv[]) { int i; for (i = 1; i < argc; i++) printf("%s%s", argv[i], (i < argc-1) ? " " : ""); printf("\n"); return 0; } *** 5.10 Command-Line Arguments: %echo hello *** stack and data segments just after the initialization of main(c,*v[]), called by %echo hello NUL L i c main's frame (stack segment) $main 2 kr115_1 Assume the binary code is saved in the file 'echo' (A) (data segment) *(v+2) *v *(v+1) v[0] v[1] v[2] v v (B) (data segment) v[0][0] v[0][1] ‘h’‘h’ ‘o’‘o’ ‘e’‘e’ ‘c’‘c’ '\0' v[0] v[1][0] v[1][1] ’\0' ‘l’‘l’ ‘l’‘l’ ‘h’‘h’ ‘e’‘e’ ’o' (C) (data segment) v[1] argv is an array of pointer to char. By convention argv is NULL-terminated, and the objects pointed by argv[i] are strings

8 Reminder : Arithmetic, Precedence and Associativity Pointer arithmetic is well defined: v+1, ++v If v is a pointer then the item pointed by v can be named by *v and v[0]; i.e. the value of v is equal to *v's address; and the value of *v is equal to v[0][0]'s address [] has higher precedence than * i.e. *v[] is equivalent to *(v[]) Associativity of [] is left to right i.e. v[][] is equivalent to (v[])[] * and ++ have same precedence, but are evaluated from right to left: *++v is equivalent to *(++v) ++*v is equivalent to ++(*v)

9 Navigation through (A) Typical Usage for (i=0; v[i] != '\0', ++i) {…} while ((++v)[0] != '\0') {…} 1. v[0] // dereferenced with the index [0] a. v[0], v[1], v[2], … or v[++i] b. v[0], (v+1)[0], (v+2)[0], … or (++v)[0] Remark With expression like *++v, be aware that the original value of v will be lost 2. *v // dereferenced with the operator * a. *v, *(v+1), *(v+2), … or *++v

10 Navigation through (B) 1_2. *v[0] // double dereferenced, first with the index [0], then with the operator * a. *v[0], *(v[0]+1), *(v[0]+2),… or *++v[0] 1_1. v[0][0] // double dereferenced with the indexes [0] and [0] a. v[0][0], v[0][1], v[0][2],… or v[0][++i] b. v[0][0], (v[0]+1)[0], (v[0]+2)[0],… or (++v[0])[0] 2_1. (*v)[0] // double dereferenced, first with the operator *, then with the index [0] a. (*v)[0], (*v)[1], (*v)[2],… or (*v)[++i] b. (*v)[0], (*v+1)[0], (*v+2)[0],… or (++*v)[0] 2_2. **v // double dereferenced with the operator * a. **v, *(*v+1), *(*v+2),… or *++*v Usage ( see kr117, line command 'find'): Navigation through B 0, C 0, … and X 1, X 2, … while ( -- argc > 0 && (*++argv)[0] == '-') while (c = *++argv[0]) // same as (c=*++argv[0]) != '\0' If you are lost, don't panic: draw a picture!

Command-Line Arguments: find [-nx] pattern Synopsis find [-nx] Description The command 'find' prints all lines that match pattern, with the options: -x: for "except", signaling the inversion (print all lines which don't contain the pattern) -n: for "number", to request line numbering main(int argc, char *argv[]) {...} Remark The complete program, which can be found in kr117, is very interesting as it contains a standard navigation through the argument 'char *argv[]' to find the options –x, -n, -xn, -nx: while (--argc>0 && (*++argv)[0] == '-') while (c = *++argv[0]) switch (c) { case 'x':... case –n':... default:... } We will come back to this program in the Series of exercises !

Pointers to Functions Prototype char *f(); // f is a constant pointer to a fct with no arg. // and returning a pointer to a variable of type char // in short: f is a function returning a pointer to char char (*f)(); // f is a variable of type pointer to a fct with no arg. // and returning a value of type char // in short: f is a pointer to a function returning a char Remark This is similar to the expressions *a[] and (*a)[] Example #include int f(int p(int), int n) {return p(n);} int g(int (*p)(int), int n) {return p(n);} int h1(int n) {return n+1;} int h2(int n) {return n+2;} main() { printf("%d %d\n", f(h1,10), g(h2,10)); }

13 *** Summary of Basic Declarations *** Basic types char c; // c is a variable of type char // in short: c is a char char *c; // c is a variable of type pointer to char // in short: c is a pointer to char Array and function char a[5]; // a is a constant pointer to an array[5] of char // in short: a is an array[5] of char char f(); // f is a constant pointer to a fct with no arg. and // returning a char // in short: f is a function returning a char Pointers char *a[5]; // a is an array[5] of pointer to char; char (*a)[5]; // a is pointer to an array[5] of char, char *f(); // f is a function returning a pointer to char char (*f)(); // f is a pointer to a function returning a char void f(char a[2]); // a is a pointer to an array[2] of char void f(char *a); // a is a pointer to a char void f(char a[]); // dito !!! // hint: in f's body, 'a' is a variable pointer come back to this slide if you are lost with pointers, arrays or functions

Complicated Declarations

typedef – first visit Examples of declarations typedef int length_t; // types int (old) and length_t (new) are synonyms typedef char *string_t; // string_t is a new type, synonym to type char * typedef int (*fct_t)(int); // fct_t is a new type, synonym to a 'pointer to a function // with one argument of type int and returning an int' Examples of usage length_t size; string_t str, a[], f(string_t); fct_t g;