POINTER AND ARRAY SUNU WIBIRAMA

Similar documents
Programming in C. Pointers and Arrays

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

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

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

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

FOR Loop. FOR Loop has three parts:initialization,condition,increment. Syntax. for(initialization;condition;increment){ body;

C Pointers. Abdelghani Bellaachia, CSCI 1121 Page: 1

Heap Arrays. Steven R. Bagley

Intermediate Programming, Spring 2017*

Dynamic memory allocation

Heap Arrays and Linked Lists. Steven R. Bagley

Programming. Pointers, Multi-dimensional Arrays and Memory Management

Dynamic Memory Allocation

Arrays and Pointers. CSE 2031 Fall November 11, 2013

Dynamic Memory Allocation (and Multi-Dimensional Arrays)

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

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

LSN 3 C Concepts for OS Programming

CS 11 C track: lecture 5

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

Dynamic memory allocation (malloc)

Week 9 Part 1. Kyle Dewey. Tuesday, August 28, 12

CS 31: Intro to Systems Pointers and Memory. Martin Gagne Swarthmore College February 16, 2016

ch = argv[i][++j]; /* why does ++j but j++ does not? */

Fundamental of Programming (C)

Memory Management. CSC215 Lecture

Kurt Schmidt. October 30, 2018

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:

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

CSCI 171 Chapter Outlines

Understanding Pointers

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

Pointers, Dynamic Data, and Reference Types

CSC 1600 Memory Layout for Unix Processes"

Arrays, Strings, & Pointers

Deep C. Multifile projects Getting it running Data types Typecasting Memory management Pointers. CS-343 Operating Systems

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

Computer Programming Unit 3

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

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

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

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

CMPS 105 Systems Programming. Prof. Darrell Long E2.371

Arrays and Pointers (part 1)

Subject: Fundamental of Computer Programming 2068

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

(13-2) Dynamic Data Structures I H&K Chapter 13. Instructor - Andrew S. O Fallon CptS 121 (November 17, 2017) Washington State University

Arrays and Memory Management

Arrays, Pointers and Memory Management

CMSC 313 COMPUTER ORGANIZATION & ASSEMBLY LANGUAGE PROGRAMMING PREVIEW SLIDES 14, SPRING 2013

Final CSE 131B Spring 2004

14. Memory API. Operating System: Three Easy Pieces

Content. In this chapter, you will learn:

IMPORTANT QUESTIONS IN C FOR THE INTERVIEW

CS61, Fall 2012 Section 2 Notes

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

Quick review pointer basics (KR ch )

Memory Management I. two kinds of memory: stack and heap

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

Memory (Stack and Heap)

Arrays and Pointers (part 1)

advanced data types (2) typedef. today advanced data types (3) enum. mon 23 sep 2002 defining your own types using typedef

PIC 10A Pointers, Arrays, and Dynamic Memory Allocation. Ernest Ryu UCLA Mathematics

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

Data Structure Series

Arrays and Pointers in C. Alan L. Cox

Character Strings. String-copy Example

CS 222: Pointers and Manual Memory Management

Introduction to C. Robert Escriva. Cornell CS 4411, August 30, Geared toward programmers

FUNCTIONS POINTERS. Pointers. Functions

Reminder of midterm 1. Next Thursday, Feb. 14, in class Look at Piazza announcement for rules and preparations

Lecture 5: Multidimensional Arrays. Wednesday, 11 February 2009

Processes. Johan Montelius KTH

A process. the stack

Variation of Pointers

CS201- Introduction to Programming Current Quizzes

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

by Pearson Education, Inc. All Rights Reserved.

Pointers and File Handling

Lecture 8 Dynamic Memory Allocation

Introduction to C. Sean Ogden. Cornell CS 4411, August 30, Geared toward programmers

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

Dynamically Allocated Memory in C

ECEN 449 Microprocessor System Design. Review of C Programming. Texas A&M University

Introduction to C. Ayush Dubey. Cornell CS 4411, August 31, Geared toward programmers

C programming basics T3-1 -

C Review. MaxMSP Developers Workshop Summer 2009 CNMAT

211: Computer Architecture Summer 2016

Memory Allocation in C

Reminder: compiling & linking

ECEN 449 Microprocessor System Design. Review of C Programming

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

Memory and C/C++ modules

o Code, executable, and process o Main memory vs. virtual memory

Outline. Computer Memory Structure Addressing Concept Introduction to Pointer Pointer Manipulation Summary

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

ELEC 377 C Programming Tutorial. ELEC Operating Systems

CS 220: Introduction to Parallel Computing. Beginning C. Lecture 2

Lab 3. Pointers Programming Lab (Using C) XU Silei

a data type is Types

Transcription:

POINTER AND ARRAY SUNU WIBIRAMA

Presentation Outline Basic Pointer Arrays Dynamic Memory Allocation

Basic Pointer 3

Pointers A pointer is a reference to another variable (memory location) in a program Used to change variables inside a function (reference parameters) Used in dynamic (on-the-fly) memory allocation (especially of arrays) Used in building complex data structures (linked lists, stacks, queues, trees, etc.)

Pointer Basics Variables are allocated at addresses in computer memory (address depends on computer/operating system) Name of the variable is a reference to that memory address A pointer variable contains a representation of an address of another variable (P is a pointer variable in the following):

Pointer Variable Definition Basic syntax: Type *Name Examples: int *P;! /* P is var that can point to an int var */ float *Q;! /* Q is a float pointer */ char *R;! /* R is a char pointer */ More example: int *AP[5]; /* AP is an array of 5 pointers to ints */ more on how to read complex declarations later

Writing Convention Mostly, we define pointer as: Type *Name But some books use: Type* Name #include <stdio.h> #include <conio.h> void main(){! int A;! int *P;! int* S;! A = 25;! P = &A;! S = &A;! printf("%i\n",*p);! printf("%i",*s);! getch(); } Result: 25 25 7

Address (&) Operator The address (&) operator can be used in front of any variable object in C -- the result of the operation is the location in memory of the variable Syntax: &VariableReference Examples: int V; int *P; int A[5]; &V /*memory location of integer variable V*/ &(A[2]) /*memory location of array element 2 in array A*/ &P /*memory location of pointer variable P*/

Pointer Variable Initialization/Assignment NULL - pointer constant to non-existent address used to indicate pointer points to nothing Can initialize/assign pointer vars to NULL or use the address (&) op to get address of a variable variable in the address operator must be of the right type for the pointer (an integer pointer points only at integer variables) Examples: int V; float W; int *P = &V; (correct) int *S = NULL; (correct) int *P = &W (error)

Indirection (*) Operator A pointer variable contains a memory address To refer to the contents of the variable that the pointer points to, we use indirection operator Syntax: *PointerVariable Example: int V = 101; int *P = &V; /* Then *P would refer to the contents of the */ /* variable V (in this case, the integer 101) */ printf( %d,*p); /* Prints 101 */

Pointers to Pointers A pointer can also be made to point to a pointer variable (but the pointer must be of a type that allows it to point to a pointer) Example: int V = 101; int *P = &V;! /* P points to int V */ int **Q = &P;! /* Q points to int pointer P */ printf( %d %d %d\n,v,*p,**q); /* prints 101 3 times */

Pointer Types Pointers are generally of the same size (enough bytes to represent all possible memory addresses), but it is inappropriate to assign an address of one type of variable to a different type of pointer Example: int V = 101; float *P = &V; /* Generally results in a Warning */ Warning rather than error because C will allow you to do this (it is appropriate in certain situations)

Casting Pointers When assigning a memory address of a variable of one type to a pointer that points to another type it is best to use the cast operator to indicate the cast is intentional (this will remove the warning) Example: int V = 101; float *P = (float *) &V; /* Casts int address to float pointer */ Removes warning, but is still a somewhat unsafe thing to do

The General (void) Pointer A void * is considered to be a general pointer No cast is needed to assign an address to a void * or from a void * to another pointer type Example: int V = 101; void *G = &V;! /* No warning */ float **P = &G; /* No warning */

Array 15

Pointers and Arrays In C/C++, there is a strong relationship between pointers and arrays. The declaration int a[10]; defines an array of 10 integers. The declaration int *p; defines p as a pointer to an int. The assignment p = a; makes p an alias for the array and sets p to point to the first element of the array. (We could also write p = &a[0];) We can now reference members of the array using either a or p a[4] = 9; p[3] = 7; int x = p[6] + a[4] * 2; 16

More Pointers and Arrays The name of an array is equivalent to a pointer to the first element of the array. Therefore, if a is the name of an array, the expression a[ i ] is equivalent to *(a + i). It follows then that &a[ i ] and (a + i) are also equivalent. Both represent the address of the i-th element beyond a. On the other hand, if p is a pointer, then it may be used with a subscript as if it were the name of an array. p[ i ] is identical to *(p + i) In short, an array-and-index expression is equivalent to a pointer-and-offset expression and vice-versa. 17

So, what s the difference? If the name of an array is synonymous with a pointer to the first element of the array, then what s the difference between an array name and a pointer? An array name can only point to the first element of its array. It can never point to anything else. A pointer may be changed to point to any variable or array of the appropriate type 18

Array Name vs Pointer int g, grades[ ] = {10, 20, 30, 40 }, mygrade = 100, yourgrade = 85, *pgrade; /* grades can be (and usually is) used as array name */ for (g = 0; g < 4; g++) printf( %d\n grades[g]); /* grades can be used as a pointer to its array if it doesn t change*/ for (g = 0; g < 4; g++) printf( %d\n *(grades + g)); /* but grades can t point anywhere else */ grades = &mygrade; /* compiler error */ /* pgrades can be an alias for grades and used like an array name */ pgrades = grades; /* or pgrades = &grades[0]; */ for( g = 0; g < 4; g++) printf( %d\n, pgrades[g]); /* pgrades can be an alias for grades and be used like a pointer that changes */ for (g = 0; g < 4; g++) printf( %d\n *pgrades++); /* BUT, pgrades can point to something else other than the grades array */ pgrades = &mygrade; printf( %d\n, *pgrades); pgrades = &yourgrade; printf( %d\n, *pgrades); 19

More Pointers & Arrays If p points to a particular element of an array, then p + 1 points to the next element of the array and p + n points n elements after p The meaning a adding 1 to a pointer is that p + 1 points to the next element in the array, REGARDLESS of the type of the array 20

Pointer Arithmetic If p is an alias for an array of ints, then p[ k ] is the k-th int and so is *(p + k). If p is an alias for an array of doubles, then p[ k ] is the k-th double and so is *(p + k). Adding a constant k to a pointer (or array name) actually adds k * sizeof(pointer type) to the value of the pointer. This is one important reason why the type of a pointer must be specified when it s defined. 21

Passing Arrays When an array is passed to a function, the address of the array is copied onto the function parameter. Since an array address is a pointer, the function parameter may be declared in either fashion. Example: int sumarray( int a[ ], int size) is equivalent to int sumarray( int *a, int size) 22

Strings revisited Recall that a string is represented as an array of characters terminated with a null (\0) character. As we ve seen, arrays and pointers are closely related. A string constant may be declared as either as in char[ ] or char* char hello[ ] = Hello Bobby ; or (almost) equivalently char *hi = Hello Bob ; 23

Arrays of Pointers Since a pointer is a variable type, we can create an array of pointers just like we can create any array of any other type. Although the pointers may point to any type, the most common use of an array of pointers is an array of char* to create an array of strings. 24

Boy s Names A common use of an array of pointers is to create an array of strings. The declaration below creates an initialized array of strings (char *) for some boys names. The diagram below illustrates the memory configuration. char *name[] = { Bobby, Jim, Harold }; name: 0 1 2 B o b b y \0 J i m \0 H a r o l d \0 25

char* array vs. char** Because the name of an array is a synonym for the address of the first element of the array, the name of the array may be treated like a pointer to the array. As a result, the name of an array of strings (for example) may be defined as either char *[ ] or char**. For example, the boy s name array char *name[] = { Bobby, Jim, Harold }; may also be defined (almost equivalently) as char **name = { Bobby, Jim, Harold }; In particular, the parameters for main may be written as either int main (int argc, char *argv[ ]) or int main( int argc, char **argv) 26

Dynamic Memory Allocation 27

Limits of Static Allocation What if we don t know how much space we will need ahead of time? Example: ask user how many numbers to read in read set of numbers in to array (of appropriate size) calculate the average (look at all numbers) calculate the variance (based on the average) Problem: how big do we make the array?? using static allocation, have to make the array as big as the user might specify (might not be big enough)

Heap in Computer Memory The operating system manages unused memory called heap It can be dynamically allocated and de-allocated (freed) 29

Dynamic Memory Allocation Allow the program to allocate some variables (notably arrays), during the program, based on variables in program (dynamically) Previous example: ask the user how many numbers to read, then allocate array of appropriate size Idea: user has routines to request some amount of memory, the user then uses this memory, and returns it when they are done Memory allocated in the Data Heap

Memory Management Functions calloc - routine used to allocate arrays of memory malloc - routine used to allocate a single block of memory realloc - routine used to extend the amount of space allocated previously free - routine used to tell program a piece of memory no longer needed Note: memory allocated dynamically does not go away at the end of functions, you MUST explicitly free it up

Array Allocation with calloc prototype: void * calloc(size_t num, size_t esize) size_t : a special type used to indicate sizes, generally an unsigned int num : the number of elements to be allocated in the array esize : the size of the elements to be allocated if not enough memory is available, calloc returns NULL

calloc Example float *nums; int N; int I; printf( Read how many numbers: ); scanf( %d,&n); nums = (float *) calloc(n, sizeof(float)); /* nums is now an array of floats of size N */ for (I = 0; I < N; I++) { printf( Please enter number %d:,i+1); scanf( %f,&(nums[i])); }

Releasing Memory (free) prototype: void free(void *ptr) memory at location pointed to by ptr is released (so we could use it again in the future) program keeps track of each piece of memory allocated by where that memory starts if we free a piece of memory allocated with calloc, the entire array is freed (released) results are problematic if we pass as address to free an address of something that was not allocated dynamically (or has already been freed)

free Example float *nums; int N; printf( Read how many numbers: ); scanf( %d,&n); nums = (float *) calloc(n, sizeof(float)); /* use array nums */ /* when done with nums: */ free(nums); /* would be an error to say it again - free(nums) */

The Importance of free void problem() { float *nums; int N = 5; nums = (float *) calloc(n, sizeof(float)); /* But no call to free with nums */ } /* problem ends */ When function problem called, space for array of size N allocated, when function ends, variable nums goes away, but the space nums points at (the array of size N) does not (allocated on the heap) - furthermore, we have no way to figure out where it is) Problem called memory leak

Array Allocation with malloc prototype: void * malloc(size_t esize) similar to calloc, except we use it to allocate a single block of the given size esize as with calloc, memory is allocated from heap NULL returned if not enough memory available memory must be released using free once the user is done

Dynamically Allocating 2D Arrays We can not simply dynamically allocate 2D (or higher) array Idea - allocate an array of pointers (first dimension), make each pointer point to a 1D array of the appropriate size Can treat result as 2D array Useful for Image Processing in C/C++ (e.g. OpenCV library)

Dynamically Allocating 2D Array float **A; /* A is an array (pointer) of float int I; pointers */ A = (float **) calloc(5,sizeof(float *)); /* A is a 1D array (size 5) of float pointers */ for (I = 0; I < 5; I++) A[I] = (float *) calloc(4,sizeof(float)); /* Each element of array points to an array of 4 float variables */ /* A[I][J] is the Jth entry in the array that the Ith member of A points to */

Non-Square 2D Arrays float **A; int I; A = (float **) calloc(5, sizeof(float *)); for (I = 0; I < 5; I++) A[I] = (float **) calloc(i+1, sizeof(float));

Presentasi Mulai minggu depan (1 April 2011) dengan tema: Stack Presenter : Bp. Riyanto dan Bp. Sapto Nugroho Petunjuk : http://te.ugm.ac.id/~wibirama/tke670/week03/ Petunjuk_Tugas_Kelompok.doc 41