Arrays and Pointers (part 2) Be extra careful with pointers!

Similar documents
Arrays and Pointers (part 2) Be extra careful with pointers!

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.

CSE2301. Arrays. Arrays. Arrays and Pointers

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

Dynamic memory allocation (malloc)

CSE2301. Arrays. Arrays. Arrays and Pointers

Quick review pointer basics (KR ch )

Summer May 18, 2010

Course organization. Course introduction ( Week 1)

Pointers. Pointer References

Array Initialization

Why arrays? To group distinct variables of the same type under a single name.

CS Programming I: Arrays

CS201- Introduction to Programming Current Quizzes

BIL 104E Introduction to Scientific and Engineering Computing. Lecture 14

Pointers. Pointers. Pointers (cont) CS 217

Lecture 14. Dynamic Memory Allocation

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

Arrays. An array is a collection of several elements of the same type. An array variable is declared as array name[size]

CSCI-243 Exam 1 Review February 22, 2015 Presented by the RIT Computer Science Community

Chapter 2 (Dynamic variable (i.e. pointer), Static variable)

Arrays, Strings, & Pointers

C Structures, Unions, Bit Manipulations, and Enumerations

C: Arrays, and strings. Department of Computer Science College of Engineering Boise State University. September 11, /16

Answer all questions. Write your answers only in the space provided. Full marks = 50

Fundamental of Programming (C)

Outline. Lecture 1 C primer What we will cover. If-statements and blocks in Python and C. Operators in Python and C

Lecture07: Strings, Variable Scope, Memory Model 4/8/2013

The output: The address of i is 0xbf85416c. The address of main is 0x80483e4. arrays.c. 1 #include <stdio.h> 3 int main(int argc, char **argv) 4 {

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

CS24 Week 2 Lecture 1

Sequential Search (Searching Supplement: 1-2)

ITC213: STRUCTURED PROGRAMMING. Bhaskar Shrestha National College of Computer Studies Tribhuvan University

just a ((somewhat) safer) dialect.

PROGRAMMAZIONE I A.A. 2017/2018

Memory. What is memory? How is memory organized? Storage for variables, data, code etc. Text (Code) Data (Constants) BSS (Global and static variables)

Class Information ANNOUCEMENTS

OBJECT ORIENTED PROGRAMMING USING C++

Warmup January 9th, What is the value of the following C expression? 8*9 % 10/ 2

Introduction. Structures, Unions, Bit Manipulations, and Enumerations. Structure. Structure Definitions

Arrays. What if you have a 1000 line file? Arrays

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

Programming. Pointers, Multi-dimensional Arrays and Memory Management

High-performance computing and programming Intro to C on Unix/Linux. Uppsala universitet

CS 261 Data Structures. Introduction to C Programming

Dynamic Memory Allocation and Command-line Arguments

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

Dynamic memory allocation

Problem 2 Add the two 2 s complement signed 8-bit values given below, and express your answer in decimal.

From Java to C. Thanks to Randal E. Bryant and David R. O'Hallaron (Carnegie-Mellon University) for providing the basis for these slides

POINTER AND ARRAY SUNU WIBIRAMA

Lecture 12 CSE July Today we ll cover the things that you still don t know that you need to know in order to do the assignment.

Strings. Chuan-Ming Liu. Computer Science & Information Engineering National Taipei University of Technology Taiwan

United States Naval Academy Electrical and Computer Engineering Department EC310-6 Week Midterm Spring AY2017

typedef int Array[10]; String name; Array ages;

Arrays. Arrays (8.1) Arrays. One variable that can store a group of values of the same type. Storing a number of related values.

Character Strings. String-copy Example

CSC209H Lecture 4. Dan Zingaro. January 28, 2015

Example: Pointer Basics

CSC 1600 Memory Layout for Unix Processes"

C PROGRAMMING Lecture 5. 1st semester

PRINCIPLES OF OPERATING SYSTEMS

CSCE150A. Introduction. Basics. String Library. Substrings. Line Scanning. Sorting. Command Line Arguments. Misc CSCE150A. Introduction.

G52CPP C++ Programming Lecture 3. Dr Jason Atkin

CS 261 Fall C Introduction. Variables, Memory Model, Pointers, and Debugging. Mike Lam, Professor

POINTER & REFERENCE VARIABLES

The C Programming Language Part 4. (with material from Dr. Bin Ren, William & Mary Computer Science, and

COP 3223 Introduction to Programming with C - Study Union - Fall 2017

Pointers, Arrays, and Strings. CS449 Spring 2016

At this time we have all the pieces necessary to allocate memory for an array dynamically. Following our example, we allocate N integers as follows:

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

Content. In this chapter, you will learn:

Overview (1A) Young Won Lim 9/25/17

A Beginner s Guide to Programming Logic, Introductory. Chapter 6 Arrays

ESC101N: Fundamentals of Computing End-sem st semester

C Programming Language

CS 241 Data Organization Pointers and Arrays

SOFTWARE Ph.D. Qualifying Exam Spring Consider the following C program which consists of two function definitions including the main function.

CMSC 313 COMPUTER ORGANIZATION & ASSEMBLY LANGUAGE PROGRAMMING LECTURE 13, FALL 2012

Friday, September 16, Lab Notes. Command line arguments More pre-processor options Programs: Finish Program 1, begin Program 2 due next week

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

C Review. MaxMSP Developers Workshop Summer 2009 CNMAT

Lecture 5: Outline. I. Multi- dimensional arrays II. Multi- level arrays III. Structures IV. Data alignment V. Linked Lists

C programming basics T3-1 -

Memory Management. a C view. Dr Alun Moon KF5010. Computer Science. Dr Alun Moon (Computer Science) Memory Management KF / 24

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

CSC209H Lecture 3. Dan Zingaro. January 21, 2015

Arrays in C C Programming and Software Tools. N.C. State Department of Computer Science

Computer Science & Engineering 150A Problem Solving Using Computers. Chapter 9. Strings. Notes. Notes. Notes. Lecture 07 - Strings

Computer Science & Engineering 150A Problem Solving Using Computers

Arrays and Pointers in C. Alan L. Cox

Ricardo Rocha. Department of Computer Science Faculty of Sciences University of Porto

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

BSM540 Basics of C Language

LAB 6 (2017 June 22/27) Array of pointers. Dynamic memory allocation.

COP 3223 Introduction to Programming with C - Study Union - Fall 2017

CS C Primer. Tyler Szepesi. January 16, 2013

Lesson 7. Reading and Writing a.k.a. Input and Output

8. Characters, Strings and Files

Transcription:

Arrays and Pointers (part 2) EECS 2031 22 October 2017 1 Be extra careful with pointers! Common errors: l Overruns and underruns Occurs when you reference a memory beyond what you allocated. l Uninitialized pointers l Null pointers de-referencing l Memory leaks l Inappropriate use of freed memory l Inappropriately freed memory 2 1

Uninitialized Pointers l Example: int *p; *p = 20; 3 Null Pointer Dereferencing main( ) { int *x; x = ( int * )malloc( sizeof( int ) ); *x = 20; /* What could go wrong? */ Better code: x = ( int * ) malloc( sizeof( int ) ); if (!x ) { printf( Insufficient memory!\n ); exit( 1 ); *x = 20; 4 2

Memory Leaks int *x; x = (int *) malloc( 20 ); x = (int *) malloc( 30 ); l The first memory block is lost for ever. l May cause problems (exhaust memory). int *x; x = (int *) malloc( 20 ); free( x ); x = (int *) malloc( 30 ); 5 Inappropriate Use of Freed Memory char *x; x = (char *) malloc( 50 ); free( x ); x[0] = A ; /* Does work on some systems though */ 6 3

Arrays of Pointers (5.6) char *words[] = { apple, cherry, banana ; l words is an array of pointers to char. (char *)(words[]) l Each element of words ( words[0], words[1], words[2]) is a pointer to char. words 0 1 2 apple cherry banana 7 Arrays vs. Pointers What is the difference between the previous example and the following? char words[][10] = { apple, cherry, banana ; 8 4

Arrays of Pointers: Example char *words[] = { apple, cherry, prune ; +1 char **p; p = words; printf("%c\n", **p); printf("%c\n",*(*(p+1)+2)); printf("%c\n",*(*(p+2)+2)+1); 9 Arrays vs. Pointers: Example 10 5

Pointers to Whole Arrays char a[10] = banana ; char *p1; char (*p2)[10]; p1 = a; /* p1 points to first element*/ p2 = &a; /* p2 points to the whole array */ printf( %c %c, *p1, **p2); // What s the difference between p1+1 and p2+1? // What s char *p3[100]? 11 Pointers to Pointers (5.6) l Pointers can point to integers, floats, chars, and other pointers. int **j; int *i; int k = 10; i = &k; j = &i; printf( %d %d %d\n, j, i, k); printf( %d %d %d\n, j, *j, **j); Output on some system: -1073744352-1073744356 10-1073744352 -1073744356 10 bffff620 bffff61c a printf( %x %x %x\n, j, *j, **j); 12 6

Multi-dimensional Arrays (5.7) int a[3][3]; int a[3][3] = { {1,2,3, {4,5,6, {7,8,9; int a[ ][3] = { {1,2,3, {4,5,6, {7,8,9; To access the elements: if ( a[2][0] == 7 ) printf (... ); for ( i=0, j=0;... ; i++, j++ ) a[i][j] = i+j; int a[ ][ ] = { {1,2,3, {4,5,6, {7,8,9; 13 Multi-dimensional Arrays (cont.) l Multi-dimensional arrays are arrays of arrays. l For the previous example, a[0] is a pointer to the first row. l Lay out in memory a[0] a[1] a[0][0] a[0][1] a[0][2] a[1][0] a[1][1] 14 7

Multi-dimensional Arrays: Example #include <stdio.h> int main() { float *pf; float m[][3]={{0.1, 0.2, 0.3, {0.4, 0.5, 0.6, {0.7, 0.8, 0.9; printf("%d \n", sizeof(m)); pf = m[1]; printf("%f %f %f \n",*pf, *(pf+1), *(pf+2)); 36 0.4000 0.5000 0.6000 15 Multi-D Arrays in Function Declarations int a[2][13]; // to be passed to function f f( int daytab[2][13] ) {... or f( int daytab[ ][13] ) {... or f( int (*daytab)[13] ) {... Note: Only to the first dimension (subscript) of an array is free; all the others have to be specified. 16 8

Initialization of Pointer Arrays (5.8) /* month_name: return name of n-th month */ char *month_name( int n ) { static char *name[] = { "Illegal month", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ; return (n < 1 n > 12)? name[0] : name[n]; 17 Pointers vs. Multi-D Arrays (5.9) int a[10][20]; int *b[10]; l a: 200 int-size locations have been set aside. l b: only 10 pointers are allocated and not initialized; initialization must be done explicitly. Assuming each element of b points to an array of 20 elements, total size = 200 integers + 10 pointers. l Advantage of b: the rows of the array may be of different lengths (saving space). 18 9

Uninitialized Pointers (cont.) l Example 1 int *p; *p = 20; l Example 2 main() { char *x[10]; strcpy( x[1], Hello ); 19 Advantage of Pointer Arrays char *name[ ] = { "Illegal month", "Jan", "Feb", "Mar" ; char aname[ ][15] = {"Illegal month", "Jan", "Feb", "Mar" ; 20 10

Command-Line Arguments (5.10) l Up to now, we define main as main(). l Usually it is defined as main( int argc, char *argv[] ) l argc is the number of arguments. l argv is a pointer to the array containing the arguments. l argv[0] is a pointer to a string with the program name. So argc is at least 1. l argv[argc] is a NULL pointer. 21 Command-Line Arguments (cont.) main( int argc, char *argv[] ) { int i; printf( Number of arg = %d\n, argc ); for( i = 0; i < argc; i++ ) printf( %s\n, argv[i] ); a.out Number of arg = 1 a.out a.out hi by 3 Number of arg = 4 a.out hi by 3 22 11

Example l Write a program name echo (echo.c) which echoes its command-line arguments on a single line, separated by blanks. l Command: l Output: echo hello, world hello, world 23 Example: Diagram l Write a program name echo (echo.c) which echoes its command-line arguments on a single line, separated by blanks. l Command: l Output: echo hello, world hello, world 24 12

echo, 1 st Version 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; 25 echo, 2 nd Version main( int argc, char *argv[] ) { while (--argc > 0) printf("%s%s", *++argv, (argc > 1)? " " : ""); printf("\n"); return 0; 26 13

Complicated Declarations (5.12) char **argv int (*daytab)[13] int *daytab[13] int *comp() argv: pointer to pointer to char daytab: pointer to array[13] of int daytab: array[13] of pointer to int comp: function returning pointer to int 27 Next lectures... l File I/O (section7.5) l Functions (chapter 4) l Introduction to UNIX (posted notes) 28 14