Chapter 16 Pointers and Arrays. 16-2 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.

Slides:



Advertisements
Similar presentations
Chapter 16 Pointers and Arrays. Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Pointers and Arrays.
Advertisements

Introduction to C Programming
Lectures 10 & 11.
Programming and Data Structure
1 Chapter 10 Strings and Pointers. 2 Introduction  String Constant  Example: printf(“Hello”); “Hello” : a string constant oA string constant is a series.
Lecture 20 Arrays and Strings
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
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.
Kernighan/Ritchie: Kelley/Pohl:
Starting out with C++1 Chapter 9 – Pointers Getting the address of a Variable Why do we have pointers? Indirection – difference between –Will you go out.
C strings (Reek, Ch. 9) 1CS 3090: Safety Critical Programming in C.
CS 61C L03 C Arrays (1) A Carle, Summer 2005 © UCB inst.eecs.berkeley.edu/~cs61c/su05 CS61C : Machine Structures Lecture #3: C Pointers & Arrays
Even More C Programming Pointers. Names and Addresses every variable has a location in memory. This memory location is uniquely determined by a memory.
Overview Pointer Variables Pass by Value Pass by Reference (or by Pointer) Arrays.
Chapter 8 Arrays and Strings
C Stack Frames / Pointer variables Stack: Local Variables Pass & Return values Frame Ptr linkage (R5) and PC linkage (R7) Pointer Variables: Defining &
CS 61C L03 C Arrays (1) A Carle, Summer 2006 © UCB inst.eecs.berkeley.edu/~cs61c/ CS61C : Machine Structures Lecture #3: C Pointers & Arrays
Programming Pointers. Variables in Memory x i c The compiler determines where variables are placed in memory This placement cannot.
CMPE-013/L: “C” Programming Gabriel Hugh Elkaim – Spring 2013 CMPE-013/L Arrays and Strings Gabriel Hugh Elkaim Spring 2013.
Chapter 19 Data Structures Data Structures A data structure is a particular organization of data in memory. We want to group related items together.
Chapter 19 Data Structures. Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Data Structures A data structure.
Chapter 17 Pointers and Arrays. Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Pointers and Arrays.
Chapter 8 Arrays and Strings
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Tevfik Bultan Lecture 12: Pointers continued, C strings.
CSC 2400 Computer Systems I Lecture 5 Pointers and Arrays.
1 Pointers and Arrays. 2 When an array is declared,  The compiler allocates sufficient amount of storage to contain all the elements of the array in.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Arrays.
ECE 103 Engineering Programming Chapter 47 Dynamic Memory Alocation Herbert G. Mayer, PSU CS Status 6/4/2014 Initial content copied verbatim from ECE 103.
1 Pointers and Strings Chapter 5 2 What You Will Learn...  How to use pointers Passing arguments to functions with pointers See relationship of pointers.
Pointers: Basics. 2 What is a pointer? First of all, it is a variable, just like other variables you studied  So it has type, storage etc. Difference:
Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee C Language Part 4.
19&20-2 Know how to declare pointer variables. Understand the & (address) and *(indirection) operators. Dynamic Memory Allocation Related Chapter: ABC.
1 Homework HW4 due today HW5 is on-line Starting K&R Chapter 5 –Skipping sections for now –Not covering section 5.12.
Pointers *, &, array similarities, functions, sizeof.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
Chapter 8 Arrays. A First Book of ANSI C, Fourth Edition2 Introduction Atomic variable: variable whose value cannot be further subdivided into a built-in.
Pointers in C++. Topics Covered  Introduction to Pointers  Pointers and arrays  Character Pointers, Arrays and Strings  Examples.
1 Pointers: Parameter Passing and Return. 2 Passing Pointers to a Function Pointers are often passed to a function as arguments  Allows data items within.
Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT:10 Advance Pointer Array, String and Dynamic Memory Allocation CS2311 Computer Programming.
C Primer Session – 1/25/01 Outline Hello World Command Line Arguments Bit-wise Operators Dynamic Memory / Pointers Function Parameters Structures.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 11: Pointers.
Array and Pointers An Introduction Unit Unit Introduction This unit covers the usage of pointers and arrays in C++
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 9-1 Pointer Variables Pointer variable : Often just called a pointer, it's.
CHAPTER 6 ARRAYS IN C 1 st semester King Saud University College of Applied studies and Community Service Csc 1101 F. Alakeel.
Chapter 5 Pointers and Arrays Ku-Yaw Chang Assistant Professor, Department of Computer Science and Information Engineering Da-Yeh.
Introduction to programming in java Lecture 21 Arrays – Part 1.
CSCI 125 & 161 / ENGR 144 Lecture 16 Martin van Bommel.
Pointers: Basics. 2 Address vs. Value Each memory cell has an address associated with it
Windows Programming Lecture 03. Pointers and Arrays.
1 Memory, Arrays & Pointers. Memory 2 int main() { char c; int i,j; double x; cijx.
DYNAMIC MEMORY ALLOCATION. Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements.
Arrays and Pointers (part 1) CSE 2031 Fall July 2016.
Computer Organization and Design Pointers, Arrays and Strings in C
User-Written Functions
Strings CSCI 112: Programming in C.
Pointers & Arrays 1-d arrays & pointers 2-d arrays & pointers.
Student Book An Introduction
Strings A string is a sequence of characters treated as a group
Lecture 6 C++ Programming
Chapter 16 Pointers and Arrays
Strings, Line-by-line I/O, Functions, Call-by-Reference, Call-by-Value
More C Stack Frames / Pointer variables
Chapter 16 Pointers and Arrays
Pointers Department of Computer Science-BGU יום רביעי 21 נובמבר 2018.
Pointers and Arrays.
Chapter 16 Pointers and Arrays
Chapter 16 Pointers and Arrays
Homework Starting K&R Chapter 5 Good tutorial on pointers
Programming in C Pointers and Arrays.
Chapter 16 Pointers and Arrays
Presentation transcript:

Chapter 16 Pointers and Arrays

16-2 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 of a variable in memory Allows us to indirectly access variables Array A list of values arranged sequentially in memory The name of the array is a pointer to where the array begins

16-3 Address vs. Value Sometimes we want to deal with the address of a memory location, rather than the value it contains. Recall example from Asgn2: adding a column of numbers. R2 contains address of first location. Read value, add to sum, and increment R2 until all numbers have been processed. R2 is a pointer -- it contains the address of data we’re interested in. x3107 x2819 x0110 x0310 x0100 x1110 x11B1 x0019 x3100 x3101 x3102 x3103 x3104 x3105 x3106 x3107 x3100 R2 address value

16-4 Another Need for Addresses Consider the following function that's supposed to swap the values of its arguments. void Swap(int first, int second) { int temp = first; first = second; second = temp; } Does this work?

16-5 Pointers in C C lets us talk about and manipulate pointers as variables and in expressions. Declaration int *p; /* p is a pointer to an int */ A pointer in C is always a pointer to a particular data type: int*, double*, char*, etc. (We’ll see why later) Operators *p -- returns the value pointed to by p &z -- returns the address of variable z

16-6 Null Pointer Sometimes we want a pointer that points to nothing. In other words, we declare a pointer, but we’re not ready to actually point to something yet. int *p; p = NULL; /* p is a null pointer */ NULL is a predefined macro that contains a value that a non-null pointer should never hold. Often, NULL = 0, because Address 0 is not a legal address for most programs on most platforms.

16-7 Using Arguments for Results Pass address of variable where you want result stored This solves the mystery of why ‘&’ with argument to scanf: scanf("%d", &data); read a decimal integer and store in data

16-8 Example using Pointers IntDivide performs both integer division and remainder, returning results via pointers. (Returns –1 if divide by zero.) int IntDivide(int x, int y, int *quoPtr, int *remPtr); main() { int dividend, divisor; /* numbers for divide op */ int quotient, remainer; /* results */ int error; /*...code for dividend, divisor input removed... */ error = IntDivide(dividend, divisor, &quotient, &remainder); /*...remaining code removed... */ }

16-9 C Code for IntDivide int IntDivide(int x, int y, int *quoPtr, int *remPtr) { if (y != 0) { *quoPtr = x / y; /* quotient in *quoPtr */ *remPtr = x % y; /* remainder in *remPtr */ return 0; } else return –1; }

16-10 Array Syntax Declaration type variable[num_elements]; Array Reference variable[index]; all array elements are of the same type number of elements must be known at compile-time Why? i-th element of array (starting with zero); no limit checking at compile-time or run-time

16-11 Array as a Local Variable Array elements are allocated as part of the activation record. int x, y; int grid[10]; int z; First element ( grid[0] ) is at lowest address of allocated space. z grid[0] grid[1] grid[2] grid[3] grid[4] grid[5] grid[6] grid[7] grid[8] grid[9] y x R5 R6

16-12 ADD R0, R5, #-11 ; R0 = grid ; z = grid[3] + 1 LDR R1, R0, #3 ; R1 = grid[3] ADD R1, R1, #1 ; plus 1 STR R1, R0, #-1 ; a = R1 ; grid[6] = 5; AND R2, R2, #0 ADD R2, R2, #5 ; R2 = 5 STR R2, R0, #6 ; grid[6] = R2 z grid[0] grid[1] grid[2] grid[3] grid[4] grid[5] grid[6] grid[7] grid[8] grid[9] y x R5 R6 R0

16-13 Passing Arrays as Arguments C passes arrays by reference the address of the array (i.e., of the first element) is written to the function's activation record otherwise, would have to copy each element main() { int numbers[MAX_NUMS]; … mean = Average(numbers, MAX_NUMS); … } /* Average can be in another file, works on ANY sized array */ int Average(int vals[], int size) { … for (index = 0; index < size; index++) sum = sum + vals[index]; return (sum / size); } This must be a constant, e.g., #define MAX_NUMS 10

16-14 A String is a Null Terminated Array of Characters Allocate space for a string just like any other array: char outputString[16]; Space for string must contain room for terminating zero. Special syntax for initializing a string: char outputString[16] = "Result = "; …which is the same as: outputString[0] = 'R'; outputString[1] = 'e'; outputString[2] = 's';... outputString[9] = ‘\0’; (or 0 or NULL)

16-15 I/O with Strings Printf and scanf use "%s" format character for string Printf -- print characters up to terminating zero printf("%s", outputString); Scanf -- read characters until whitespace, store result in string, and terminate with zero scanf("%s", inputString);

16-16 Relationship between Arrays and Pointers An array name is essentially a pointer to the first element in the array char word[10]; char *cptr; cptr = word; /* points to word[0] */ Difference: Can change the contents of cptr, as in cptr = &someString; cptr = cptr + 1; (The identifier "word" is not a variable.)

16-17 Correspondence between Ptr and Array Notation Given the declarations on the previous page, each line below gives three equivalent expressions: cptr word &word[0] &cptr[0] (cptr + 3) word + 3 &word[3] &cptr[3] *cptr *word word[0] cptr[0] *(cptr + 3) *(word + 3) word[3] cptr[3]

16-18 Common Pitfalls with Arrays in C Overrun array limits There is no checking at run-time or compile-time to see whether reference is within array bounds. int i; int array[10]; for (i = 0; i <= 10; i++) array[i] = 0; Declaration with variable size Size of array must be known at compile time. void SomeFunction(int num_elements) { int temp[num_elements]; (can’t do this!) … } Solutions (more on this later): int *temp = (int *) malloc(sizeof(int)*num_elements);

16-19 Pointer Arithmetic Address calculations depend on size of elements In our LC-3 code, we've been assuming one word per element.  e.g., to find 4th element, we add 4 to base address It's ok, because we've only shown code for int and char, both of which take up one word. If double, we'd have to add 8 to find address of 4th element. C does size calculations under the covers, depending on size of item being pointed to: double x[10]; double *y = x; *(y + 3) = 13; allocates 80 bytes (8 per element) same as x[3] -- base address plus 24

16-20 Using strings in C #include int strlen(char *); char *strcpy(char *dest, char *src); char *strncpy(char *dest, char *src, int maxlen); int strcmp(char *a, char *b); <0 if a before b in alphabetical order 0 if string a is same as string b >0 if a after b in alphabetical order char *strtok(char *a, char *tokens); Place a ‘\0’ at first occurrence of a token, return a char *strtok(NULL, char *tokens); Starting where it left off, divide at token, return next portion type “man strlen” for more details

16-21 int strlen(char *s) Treated as an array: int strlen(char s[]) { int length = 0; while (s[length] != ‘\0’) length++; return length; } Treated as a pointer: int strlen(char *s) { int length = 0; while (*(s++) != ‘\0’) { length++;} return length; }