Arrays, Pointers and Memory Management

Similar documents
Arrays and Pointers (part 1)

Arrays and Pointers (part 1)

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

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.

Summer May 18, 2010

[0569] p 0318 garbage

CSE2301. Arrays. Arrays. Arrays and Pointers

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

EM108 Software Development for Engineers

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

Assist. Prof. Dr. Caner ÖZCAN

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

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

CSE2301. Arrays. Arrays. Arrays and Pointers

Pointers. Variable Declaration. Chapter 10

Multidimension array, array of strings

SYSC 2006 C Winter 2012

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

Course organization. Course introduction ( Week 1)

Intermediate Programming, Spring 2017*

Homework #3 CS2255 Fall 2012

CS201- Introduction to Programming Current Quizzes

MYcsvtu Notes LECTURE 34. POINTERS

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

CprE 288 Introduction to Embedded Systems Exam 1 Review. 1

Pointers, Dynamic Data, and Reference Types

What is Pointer? Pointer is a variable that holds a memory address, usually location of another variable.

Dynamic Memory Allocation

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

dynamic memory allocation

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

Memory Allocation in C

Procedural programming with C

CS 11 C track: lecture 5

Pointers and File Handling

Lecture 14. No in-class files today. Homework 7 (due on Wednesday) and Project 3 (due in 10 days) posted. Questions?

Understanding Pointers

C Syntax Arrays and Loops Math Strings Structures Pointers File I/O. Final Review CS Prof. Jonathan Ventura. Prof. Jonathan Ventura Final Review

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

Memory, Arrays & Pointers

Chapter-11 POINTERS. Important 3 Marks. Introduction: Memory Utilization of Pointer: Pointer:

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

Dynamic Allocation in C

Pointers as Arguments

Dynamic memory allocation (malloc)

C Pointers. Abdelghani Bellaachia, CSCI 1121 Page: 1

Dynamic Data Structures. CSCI 112: Programming in C

Scheme G. Sample Test Paper-I. Course Name : Computer Engineering Group Course Code : CO/CD/CM/CW/IF Semester : Second Subject Tile : Programming in C

Strings Investigating Memory Allocation Pointers Fixed-Point Arithmetic. Memory Matters. Embedded Systems Interfacing.

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

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

Unit IV & V Previous Papers 1 mark Answers

Quick review pointer basics (KR ch )

CS107 Handout 08 Spring 2007 April 9, 2007 The Ins and Outs of C Arrays

Subject: Fundamental of Computer Programming 2068

Kurt Schmidt. October 30, 2018

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

Pointers. Introduction

Fundamental of Programming (C)

EL2310 Scientific Programming

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

CSCI 2212: Intermediate Programming / C Review, Chapters 10 and 11

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

Computer Programming Unit 3

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

Programming. Pointers, Multi-dimensional Arrays and Memory Management

Declaring Pointers. Declaration of pointers <type> *variable <type> *variable = initial-value Examples:

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

3/22/2016. Pointer Basics. What is a pointer? C Language III. CMSC 313 Sections 01, 02. pointer = memory address + type

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

10/20/2015. Midterm Topic Review. Pointer Basics. C Language III. CMSC 313 Sections 01, 02. Adapted from Richard Chang, CMSC 313 Spring 2013

POINTER AND ARRAY SUNU WIBIRAMA

CME 112- Programming Languages II. Week 4 Pointers

Pointer Arithmetic. Lecture 4 Chapter 10. Robb T. Koether. Hampden-Sydney College. Wed, Jan 25, 2017

Gabriel Hugh Elkaim Spring CMPE 013/L: C Programming. CMPE 013/L: C Programming

Structures and Pointers

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

WHAT POINTERS REALLY ARE

Dynamic Allocation in C

Final Intro to C Review

ECE 15B COMPUTER ORGANIZATION

CS61C : Machine Structures

IMPORTANT QUESTIONS IN C FOR THE INTERVIEW

PROGRAMMAZIONE I A.A. 2017/2018

C Structures & Dynamic Memory Management

CMSC 313 COMPUTER ORGANIZATION & ASSEMBLY LANGUAGE PROGRAMMING LECTURE 13, SPRING 2013

CS 61c: Great Ideas in Computer Architecture

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

CS 31: Intro to Systems Pointers and Memory. Kevin Webb Swarthmore College October 2, 2018

Algorithms & Data Structures

Content. In this chapter, you will learn:

Memory and Addresses. Pointers in C. Memory is just a sequence of byte-sized storage devices.

Pointers. Lecture 2 Sections Robb T. Koether. Hampden-Sydney College. Fri, Jan 18, 2013

More Pointers Week 11

Pointers. Pointers. Pointers (cont) CS 217

Pointers and Arrays CS 201. This slide set covers pointers and arrays in C++. You should read Chapter 8 from your Deitel & Deitel book.

Intermediate Programming, Spring 2017*

Chapter-8 DATA TYPES. Introduction. Variable:

C Pointers. Indirection Indirection = referencing a value through a pointer. Creating Pointers. Pointer Declarations. Pointer Declarations

Transcription:

Arrays, Pointers and Memory Management EECS 2031 Summer 2014 Przemyslaw Pawluk May 20, 2014

Answer to the question from last week strct->field Returns the value of field in the structure pointed to by strct. s t r u c t p e r s o n { i n t age, s a l a r y ; DEPT department ; char name [ 1 2 ] ; char a d d r e s s [ 6 ] [ 2 0 ] ; } ; typedef s t r u c t p e r s o n EMPLOYEE; EMPLOYEE Emp ;... p r i n t f ( Age : %d\n,emp >age ) ;

What we will discuss today Arrays Pointers Pointers Pointers and Arrays Memory management Homework

Table of Contents Arrays Pointers Pointers Pointers and Arrays Memory management Homework

Array What is an Array? is grouping of data of the same type is continuous block of memory programmers set array sizes explicitly can be multidimensional (defined as array of arrays) loops are commonly used to manipulate data

Example Syntax type name [ s i z e ] ; Declaration examples i n t b i g A r r a y [ 1 0 ] ; // a r r a y o f i n t s o f s i z e 10 double a [ 3 ] ; // a r r a y o f d o u b l e s o f s i z e 3 char grade [ 1 0 ], onegrade ; // c h a r s o f s i z e 10 char s t r i n g s [ ] ; // a r r a y o f s t r i n g s i n t m u l t i A r r a y [ ] [ ] ; // two d i m e n s i o n a l

Example Definition of the array allocates the memory type arrname[size] Individual elements can be extracted/called Using and index called also a subscript you can access array elements Example i n t s c o r e [ 5 ] ; / A l l o c a t e s f i v e ( 5 ) a d j a c e n t b l o c k s o f memory f o r i n t / s c o r e [ 0 ] = 100; / s e t s a v a l u e f o r f i r s t element i n the a r r a y /

Array in the memory Example i n t a r r [ 3 ] = { 1, 2, 3 } ; single block is a byte each integer occupies 4 bytes in the memory first element (index 0) stretches from byte 0 to byte 3 Note: It is an example, in the memory addresses will not start from 0!

Initialization Static variables int a[5] = {22,51} declares array and init first two elements, remaining elements are 0 int b[] = {1, 3, 22, 51, 4} b has 5 elements listed in curly brackets If the initialization is empty, elements are initialized with value 0 (for a specific type) Examples int c[10]; array consisting 10 values 0 float d[10]; array consisting 10 values 0.0f char *str[5]; array of 5 NULL

Arrays and indexes Syntax arrayname[index] Examples x = ar[2]; ar[3] = 2.7; Question What is the difference between the following expressions? ar[i]++ increment value of i th element ar[i++] access i th value and move index ar[++i] move index and access i th value

Arrays and indexes Syntax arrayname[index] Examples x = ar[2]; ar[3] = 2.7; Question What is the difference between the following expressions? ar[i]++ increment value of i th element ar[i++] access i th value and move index ar[++i] move index and access i th value

Arrays and indexes Syntax arrayname[index] Examples x = ar[2]; ar[3] = 2.7; Question What is the difference between the following expressions? ar[i]++ increment value of i th element ar[i++] access i th value and move index ar[++i] move index and access i th value

Arrays and indexes Syntax arrayname[index] Examples x = ar[2]; ar[3] = 2.7; Question What is the difference between the following expressions? ar[i]++ increment value of i th element ar[i++] access i th value and move index ar[++i] move index and access i th value

Arrays and indexes Syntax arrayname[index] Examples x = ar[2]; ar[3] = 2.7; Question What is the difference between the following expressions? ar[i]++ increment value of i th element ar[i++] access i th value and move index ar[++i] move index and access i th value

Table of Contents Arrays Pointers Pointers Pointers and Arrays Memory management Homework

Variables, Pointer and Addresses Variable Variable is a named block of memory of a specific type e.g. int x; or float y; or char* str; Pointer Pointer is a type of variable which value is an address of a variable in the memory, Syntax: type * variablename; Example: char* str; or int* iptr; or float* fptr; Address Address is a number representing an index of the first memory block of the variable (where does it start in the memory) Use address of operator to get the address of the variable pointer_variable = &ordinary_variable

Variables, Pointer and Addresses Variable Variable is a named block of memory of a specific type e.g. int x; or float y; or char* str; Pointer Pointer is a type of variable which value is an address of a variable in the memory, Syntax: type * variablename; Example: char* str; or int* iptr; or float* fptr; Address Address is a number representing an index of the first memory block of the variable (where does it start in the memory) Use address of operator to get the address of the variable pointer_variable = &ordinary_variable

Variables, Pointer and Addresses Variable Variable is a named block of memory of a specific type e.g. int x; or float y; or char* str; Pointer Pointer is a type of variable which value is an address of a variable in the memory, Syntax: type * variablename; Example: char* str; or int* iptr; or float* fptr; Address Address is a number representing an index of the first memory block of the variable (where does it start in the memory) Use address of operator to get the address of the variable pointer_variable = &ordinary_variable

Table of Contents Arrays Pointers Pointers Pointers and Arrays Memory management Homework

Pointers and Operators & operator address of variable * operator value pointed by the pointer Example: i n t p1, v1 ; v1 = 0 ; p1 = &v1 ; p1 = 4 2 ; p r i n t f ( %d\ n, v1 ) ; p r i n t f ( %d\n, p1 ) ; Result: 42 42 Note Assigning a value for a pointer variable manually is a bad idea! e.g. int *p1; p1=2341

Pointers and Function Arguments C passes arguments to functions by values Question: What is the difference between these two functions? Function 1 void swap ( i n t x, i n t y ) { i n t temp ; temp = x ; x = y ; y = temp ; } Function 2 void swap ( i n t px, i n t py ) { i n t temp ; temp = px ; px = py ; py = temp ; }

Table of Contents Arrays Pointers Pointers Pointers and Arrays Memory management Homework

Pointers and Arrays Identifier of an array is equivalent to the address of its first element. i n t numbers [ 2 0 ] ; i n t p ; p = numbers ; // V a l i d numbers = p ; // I n v a l i d

Arrays and Pointer Arithmetics Array can be iterated using a pointer and * operator Example i n t a [ ] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 1 0 } ; i n t pa ; i n t x, y, z ; pa = &a [ 0 ] ; // a=pa i s i l l e g a l ; // a++ i s i l l e g a l // but pa++ i s OK x = pa ; // x==1 y = ( pa + 1 ) ; z = ( pa + 2 ) ; // y==2 // z==3

Pointer Arithmetics cont. Given pointers p and q of the same type and integer n, the following pointer operations are legal: 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. q p, q p + 10, q p + n (assuming q > p) But p + q is illegal! q = p; p = q + 100; If p and q point to different types, must cast first. Otherwise, the assignment is illegal! if ( p == q ), if ( p = q + n )! p = NULL; if ( p == NULL ), same as if (!p )

Pointer Arithmetics Summary 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) 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

Pointer Arithmetics Summary 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) 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

Sub-arrays Pointer can be used to access a sub-array and pass it to a function Examples my_func( int ar[ ] ) {...} or my_func( int *ar ) {...} my_func(&a[5]); or my_func(a + 5);

Character Pointers A string constant ("hello world") is an array of characters. The array is terminated with the null character \0 so that programs can find the end. Example char pmessage ; pmessage = now i s the time ; Assigns to pmessage a pointer to the first character in the array. This is not a string copy; only pointers are involved.

What is the difference? char amessage [ ] = now i s the time ; char pmessage = now i s the time ; amessage will always refer to the same storage. pmessage may later be modified to point elsewhere. Note C does not provide any operators for processing an entire string of characters as a unit.

What is the difference? char amessage [ ] = now i s the time ; char pmessage = now i s the time ; amessage will always refer to the same storage. pmessage may later be modified to point elsewhere. Note C does not provide any operators for processing an entire string of characters as a unit.

What is the difference? char amessage [ ] = now i s the time ; char pmessage = now i s the time ; amessage will always refer to the same storage. pmessage may later be modified to point elsewhere. Note C does not provide any operators for processing an entire string of characters as a unit.

Table of Contents Arrays Pointers Pointers Pointers and Arrays Memory management Homework

Problem following is not allowed in C i n t x = 1 0 ; i n t my array [ x ] ; How to allocate memory during run time? Use functions to allocate (reserve) memory on heap, e.g. malloc(), calloc(), realloc()

Problem following is not allowed in C i n t x = 1 0 ; i n t my array [ x ] ; How to allocate memory during run time? Use functions to allocate (reserve) memory on heap, e.g. malloc(), calloc(), realloc()

malloc() Defined in stdlib.h Signature void *malloc( int n ); Allocates memory at run time. Returns a pointer (to a void, void*) to at least n bytes available. Returns null if the memory was not allocated. The allocated memory is not initialized.

calloc() Defined in stdlib.h Signature void *calloc( int n, int s ); Allocates an array of n elements where each element has size s calloc() initializes the allocated memory all to 0.

realloc() Defined in stdlib.h Signature void *realloc( void *ptr, int n ); Resizes a previously allocated block of memory. ptr must have been returned from a previous calloc, malloc, or realloc The new array may be moved if it cannot be extended in its current location.

free() Defined in stdlib.h Signature void free( void *ptr ); Releases the memory we previously allocated. ptr must have been returned from a previous calloc, malloc, or realloc. Note: C does not do automatic garbage collection

Example #include <s t d i o. h> #include <s t d l i b. h> i n t main ( ) { i n t a, i, n, sum = 0 ; p r i n t f ( I n p u t an a r r a y s i z e : ) ; s c a n f ( %d, &n ) ; a = m a l l o c ( n s i z e o f ( i n t ) ) ; / a = c a l l o c ( n, s i z e o f ( i n t ) ) ; / f o r ( i =0; i <n ; i++ ) s c a n f ( %d, &a [ i ] ) ; f o r ( i =0; i <n ; i++ ) sum += a [ i ] ; f r e e ( a ) ; p r i n t f ( Number o f e l e m e n t s = %d\n, n ) ; p r i n t f ( Sum i s %d\n, sum ) ; }

Table of Contents Arrays Pointers Pointers Pointers and Arrays Memory management Homework

Homework Create a simple C program that: Reads a file called input.txt that contains a single integer number. Let s call it N Allocate an array of char of size N Reads N-1 characters from input Saves them at the end into the file output.txt Frees the memory allocated for the array