Pointers (part 1) What are pointers? EECS We have seen pointers before. scanf( %f, &inches );! 25 September 2017

Similar documents
Arrays and Pointers (part 1)

Arrays and Pointers (part 1)

Arrays and Pointers. CSE 2031 Fall November 11, 2013

Arrays and Pointers. Arrays. Arrays: Example. Arrays: Definition and Access. Arrays Stored in Memory. Initialization. EECS 2031 Fall 2014.

Arrays, Pointers and Memory Management

CSE2301. Arrays. Arrays. Arrays and Pointers

Multidimension array, array of strings

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

SYSC 2006 C Winter 2012

CSE2301. Arrays and Pointers. These slides are based on slides by Prof. Wolfgang Stuerzlinger at York University. Arrays

CSE2301. Arrays. Arrays. Arrays and Pointers

Quick review pointer basics (KR ch )

Course organization. Course introduction ( Week 1)

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

Other C materials before pointer Common library functions [Appendix of K&R] 2D array, string manipulations. <stdlib.

Pointers. Part VI. 1) Introduction. 2) Declaring Pointer Variables. 3) Using Pointers. 4) Pointer Arithmetic. 5) Pointers and Arrays

EM108 Software Development for Engineers

Dynamic memory allocation (malloc)

Basic and Practice in Programming Lab7

Agenda. Peer Instruction Question 1. Peer Instruction Answer 1. Peer Instruction Question 2 6/22/2011

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

Language comparison. C has pointers. Java has references. C++ has pointers and references

Intermediate Programming, Spring 2017*

Dynamic Allocation in C

Content. In this chapter, you will learn:

int marks[10]; // fixed size and fixed address No change in Memory address.

Week 5 9 April 2018 NWEN 241 More on pointers. Alvin Valera. School of Engineering and Computer Science Victoria University of Wellington

Pointers. Pointers. Pointers (cont) CS 217

Dynamic Memory Allocation

Memory, Arrays & Pointers

CS113: Lecture 5. Topics: Pointers. Pointers and Activation Records

Dynamic Allocation in C

Aryan College. Fundamental of C Programming. Unit I: Q1. What will be the value of the following expression? (2017) A + 9

Pointers and File Handling

Procedural programming with C

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

CS 61C: Great Ideas in Computer Architecture. C Arrays, Strings, More Pointers

... Lecture 12. Pointers

Variation of Pointers

CS 61c: Great Ideas in Computer Architecture

Subject: Fundamental of Computer Programming 2068

Character Strings. String-copy Example

Lectures 5-6: Introduction to C

Dynamic Data Structures. CSCI 112: Programming in C

Pointers. Pointer References

CSE2301. Dynamic memory Allocation. malloc() Dynamic Memory Allocation and Structs

PDS Class Test 2. Room Sections No of students

Memory Allocation in C

[0569] p 0318 garbage

Announcements. assign0 due tonight. Labs start this week. No late submissions. Very helpful for assign1

More Pointers Week 11

Unit IV & V Previous Papers 1 mark Answers

Review: C Strings. A string in C is just an array of characters. Lecture #4 C Strings, Arrays, & Malloc

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

Jagannath Institute of Management Sciences Lajpat Nagar. BCA II Sem. C Programming

Pointers and Structure. Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island

Chapter 16. Pointers and Arrays. Address vs. Value. Another Need for Addresses

Structures and Pointers

Practice Sheet #07 with Solutions

MYcsvtu Notes LECTURE 34. POINTERS

mith College Computer Science CSC270 Spring 2016 Circuits and Systems Lecture Notes, Week 11 Dominique Thiébaut

Pointers as Arguments

Computer Programming. C Array is a collection of data belongings to the same data type. data_type array_name[array_size];

Introduction to Scientific Computing and Problem Solving

POINTERS. Content. Pointers. Benefits of Pointers. In this chapter, you will learn:

Arrays, Strings, and Pointers

Programming. Pointers, Multi-dimensional Arrays and Memory Management

A pointer is a variable just like other variable. The only difference from other variables is that it stores the memory address other variables.

Lectures 5-6: Introduction to C

Arrays, Strings, and Pointers

CSE 230 Intermediate Programming in C and C++ Arrays, Pointers and Strings

dynamic memory allocation

APS105. Malloc and 2D Arrays. Textbook Chapters 6.4, Datatype Size

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

Pointer in C SHARDA UNIVERSITY. Presented By: Pushpendra K. Rajput Assistant Professor

Fundamental of Programming (C)

MIDTERM TEST EESC 2031 Software Tools June 13, Last Name: First Name: Student ID: EECS user name: TIME LIMIT: 110 minutes

CS61C : Machine Structures

K. N. King: chapters 8 and 12

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

M4.1-R3: PROGRAMMING AND PROBLEM SOLVING THROUGH C LANGUAGE

Why Pointers. Pointers. Pointer Declaration. Two Pointer Operators. What Are Pointers? Memory address POINTERVariable Contents ...

Reference slides! Garcia, Fall 2011 UCB! CS61C L04 Introduction to C (pt 2) (1)!

Number Review. Lecture #3 More C intro, C Strings, Arrays, & Malloc Variables. Clarification about counting down

Systems Programming and Computer Architecture ( )

CS61C Machine Structures. Lecture 5 C Structs & Memory Mangement. 1/27/2006 John Wawrzynek. www-inst.eecs.berkeley.edu/~cs61c/

Computer Programming Unit 3

Introduction to C Language (M3-R )

Kurt Schmidt. October 30, 2018

Personal SE. Functions, Arrays, Strings & Command Line Arguments

C BOOTCAMP DAY 2. CS3600, Northeastern University. Alan Mislove. Slides adapted from Anandha Gopalan s CS132 course at Univ.

Arrays and Pointers in C. Alan L. Cox

A Shotgun Introduction to C

C-LANGUAGE CURRICULAM

What have we learned about when we learned about function parameters? 1-1

Department of Computer Science & Engineering Indian Institute of Technology Kharagpur. Practice Sheet #07. Topic: Pointer in C Date:

Agenda. Components of a Computer. Computer Memory Type Name Addr Value. Pointer Type. Pointers. CS 61C: Great Ideas in Computer Architecture

CS 137 Part 5. Pointers, Arrays, Malloc, Variable Sized Arrays, Vectors. October 25th, 2017

Structures. Basics of Structures (6.1) EECS l Now struct point is a valid type. l Defining struct variables: struct point { int x; int y; };

Homework #3 CS2255 Fall 2012

Transcription:

Pointers (part 1) EECS 2031 25 September 2017 1 What are pointers? We have seen pointers before. scanf( %f, &inches );! 2 1

Example char c; c = getchar(); printf( %c, c); char c; char *p; c = getchar(); p = &c; printf( %c, *p); 3 Pointers and Addresses (5.1) Use the "address of" operator (&) General form: pointer_variable = &ordinary_variable Name of the pointer Name of ordinary variable 4 2

Pointers Variables l Pointer = memory address of a variable l Declared with data type, * and identifier type *pointer_var1, *pointer_var2, ; l Example. double *p; int *p1, *p2; l There has to be a * before each of the pointer variables 5 Using a Pointer Variable l Can be used to access a value l Use unary operator * *pointer_variable In executable statement, indicates value l Example int *p1, v1; v1 = 0; p1 = &v1; *p1 = 42; printf( %d\n,v1); printf( %d\n,*p1); Output: 42 42 6 3

Pointer Example 1 int x, y; int *z; x = 25; y = x; z = &x; x 1200 1204 1208 25 25 1204 y 9608 8404 z 7 Pointer Variables z = 1024 BAD idea Instead, use z = &x 8 4

Pointer Example 2 y 8404 1204 int x = 25, *y, z; y = &x; z = *y; x 1200 1204 1208 25 9608 25 z 9 Pointer Example 3 int *p1, *p2, x = 8, y = 9; p1 = &x; p2 = &y; 10 5

More Examples int x = 1, y = 2, z[10], k; int *ip; ip = &x; /* ip points to x*/ y = *ip; /* y is now 1 */ *ip = 0; /* x is now 0 */ z[0] = 0; ip = &z[0]; /* ip points to z[0] */ for (k = 0; k < 10; k++) z[k] = *ip + k; *ip = *ip + 100; ++*ip; (*ip)++; /* How about *ip++??? */ 11 Precedence and Associativity 12 6

Pointers and Function Arguments (5.2) Write a function that swaps the contents of two integers a and b. void main( ) { int a, b; /* Input a and b */ swap(a, b); printf( %d %d, a, b); { C passes arguments to functions by values (as Java does) void swap(int x, int y) { int temp; temp = x; x = y; y = temp; } 13 The Correct Version void swap(int *px, int *py) { int temp; temp = *px; *px = *py; *py = temp; } void main( ) { int a, b; /* Input a and b */ swap(&a, &b); printf( %d %d, a, b); { 14 7

Pointers and Arrays 15 Pointers and Arrays (5.3) l Identifier of an array is equivalent to the address of its first element. int numbers[20]; int *p; p = numbers numbers = p // valid // invalid l p and numbers are equivalent and they have the same properties. l Only difference is that we could assign another value to the pointer p whereas numbers will always point to the first of the 20 integer numbers of type int. 16 8

Pointers and Arrays: Example int a[10]; /* Init a[i] = i */ int *pa; pa = &a[0] /*same as pa = a */ x = *pa; /*same as x = a[0]*/ int y, z; y = *(pa + 1); z = *(pa + 2); 17 Pointers and Arrays: More Examples int a[10], *pa; pa = a; /* same as pa = &a[0]*/ pa++; /*same as pa = &a[1]*/ a[i] *(a+i) &a[i] a+i pa[i] *(pa+i) Notes a = pa; a++; are illegal. Think of a as a constant, not a modifiable variable. p[-1], p[-2], etc. are syntactically legal. 18 9

Accessing Arrays Using Pointers Note the use of (data + i) Note the use of *(data + i)! 19 Homework l Lab 2, problem B: Write a C program to input a set of integers, store them in an array, find the maximum and minimum values of the set, and display those two values. l Lab 3, problem A: Write a C program to input a line of characters and store the input characters in an array. Reverse the order of the input characters and display the reversed string on the standard output using printf. l This time access elements of the arrays using pointers, not array indexing. 20 10

Arrays Passed to a Function l Arrays passed to a function are passed by reference. l The name of the array is a pointer to its first element. 21 Computing String Lengths /* strlen: return length of string s */ int strlen( char *s ) /* or ( char s[] ) */ { int n; for ( n = 0; *s!= '\0', s++ ) n++; return n; } Callers: strlen( "hello, world ); /* string constant */ char array[100]; /* then input a string into array */ strlen( array ); char *ptr = array; strlen( ptr ); 22 11

Passing Sub-arrays to Functions l It is possible to pass part of an array to a function, by passing a pointer to the beginning of the sub-array. l Function my_func( int arr[ ] ) {...} or my_func( int *arr ) {...} Caller: int a[100]; my_func(&a[5]); or my_func(a + 5); 23 Address Arithmetic (5.4) Given pointers p and q of the same type and integer n, the following pointer operations are legal: l p + n, p n n is scaled according to the size of the objects p points to. If p points to an integer of 4 bytes, p + n advances by 4*n bytes. l q p, q p + 10, q p + n (assuming q > p) But p + q is illegal! l q = p; p = q + 100; If p and q point to different types, must cast first. Otherwise, the assignment is illegal! l if ( p == q ), if ( p!= q + n ) l p = NULL; l if ( p == NULL ), same as if (!p ) 24 12

Address Arithmetic: Example /* strlen: return length of string s */ int strlen(char *s) { } char *p = s; while (*p!= '\0') p++; return p - s; 25 Address Arithmetic: Summary l Legal: assignment of pointers of the same type adding or subtracting a pointer and an integer subtracting or comparing two pointers to members of the same array assigning or comparing to zero (NULL) l Illegal: add two pointers multiply or divide or shift or mask pointer variables add float or double to pointers assign a pointer of one type to a pointer of another type (except for void *) without a cast 26 13

Character Pointers and Functions (5.5) l A string constant ( hello world ) is an array of characters. l The array is terminated with the null character '\0' so that programs can find the end. char *pmessage; pmessage = "now is the time"; assigns to pmessage a pointer to the character array. This is not a string copy; only pointers are involved. C does not provide any operators for processing an entire string of characters as a unit. 27 Important Difference between... char amessage[] = "now is the time"; /* an array */ char *pmessage = "now is the time"; /* a pointer */ l amessage will always refer to the same storage. l pmessage may later be modified to point elsewhere. 28 14

Example: String Copy Function /* strcpy: copy t to s; array subscript version */ void strcpy(char *s, char *t) { int i; i = 0; while ((s[i] = t[i])!= '\0') i++; } /* strcpy: copy t to s; pointer version */ void strcpy(char *s, char *t) { int i; i = 0; while ((*s = *t)!= '\0') { s++; t++; } } /* strcpy: copy t to s; pointer version 2 */ void strcpy(char *s, char *t) { while ((*s++ = *t++)!= '\0') ; } 29 Dynamic Memory Allocation EECS 2031 25 September 2017 30 15

Dynamic Memory Allocation (7.8.5) l How to allocate memory during run time? l Example: input an integer n. Allocate an array of size n. int n; scanf( %d, &n ); int my_array[ n ]; /* not allowed in C */ 31 malloc() l In stdlib.h void *malloc( int n ); l Allocates memory at run time. l Returns a pointer (to a void) to at least n bytes available. l Returns null if the memory was not allocated. l The allocated memory is not initialized. 32 16

Example #include<stdio.h> #include<stdlib.h> main() { int *a, i, n, sum=0; printf( Input an aray size ); scanf( %d, &n ); a = malloc ( n * sizeof(int) ); for( i=0; i<n; i++ ) scanf( %d, &a[i] ); for( i=0; i<n; i++ ) sum += a[i]; free( a ); printf( Number of elements = %d and the sum is %d\n, n, sum); } 33 calloc() void *calloc( int n, int s ); l Allocates an array of n elements where each element has size s; l calloc( ) initializes the allocated memory all to 0. 34 17

realloc() l What if we want our array to grow (or shrink)? void *realloc( void *ptr, int n ); l Resizes a previously allocated block of memory. l ptr must have been returned from a previous calloc, malloc, or realloc. l The new array may be moved if it cannot be extended in its current location. 35 free() void free( void *ptr ) l Releases the memory we previously allocated. l ptr must have been returned from a previous calloc, malloc, or realloc. l C does not do automatic garbage collection. 36 18

Example #include<stdio.h> #include<stdlib.h> main() { int *a, i, n, sum=0; printf( Input an aray size ); scanf( %d, &n ); a = calloc( n, sizeof(int) ); /* a = malloc ( n * sizeof(int) ) */ for( i=0; i<n; i++ ) scanf( %d, &a[i] ); for( i=0; i<n; i++ ) sum += a[i]; free( a ); printf( Number of elements = %d and the sum is %d\n, n, sum); } 37 Next time... l Structures (Chapter 6) 38 19