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:

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

Dynamic Memory Allocation (and Multi-Dimensional Arrays)

Dynamic Data Structures. CSCI 112: Programming in C

Arrays in C. Data and File Structures Laboratory. DFS Lab (ISI) Arrays in C 1 / 1

DECLARAING AND INITIALIZING POINTERS

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

Assist. Prof. Dr. Caner ÖZCAN

Character Strings. String-copy Example

Pointers. A pointer is simply a reference to a variable/object. Compilers automatically generate code to store/retrieve variables from memory

Understanding Pointers

Pointers. Memory. void foo() { }//return

Heap Arrays. Steven R. Bagley

Dynamic Memory Management. Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island

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

Arrays. Example: Run the below program, it will crash in Windows (TurboC Compiler)

Dynamically Allocated Memory in C

Lecture 5: Multidimensional Arrays. Wednesday, 11 February 2009

M3-R4: PROGRAMMING AND PROBLEM SOLVING THROUGH C LANGUAGE

POINTER AND ARRAY SUNU WIBIRAMA

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #33 Pointer Arithmetic

CS 222: Pointers and Manual Memory Management

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

Reference operator (&)

Dynamic Memory Allocation and Command-line Arguments

CSC 1600 Memory Layout for Unix Processes"

Pointers. Reference operator (&) ted = &andy;

CS201- Introduction to Programming Current Quizzes

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

Laboratory 10 POINTERS I. FUNDAMENTALS

CS 61C: Great Ideas in Computer Architecture. Lecture 3: Pointers. Krste Asanović & Randy Katz

Data Representation and Storage. Some definitions (in C)

CS 11 C track: lecture 5

Structures and Pointers

ESC101N: Fundamentals of Computing End-sem st semester

Goals of this Lecture

Actually, C provides another type of variable which allows us to do just that. These are called dynamic variables.

by Pearson Education, Inc. All Rights Reserved.

Dynamic memory allocation

FUNCTIONS POINTERS. Pointers. Functions

CS24 Week 2 Lecture 1

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

COMP26120: Pointers in C (2018/19) Lucas Cordeiro

Arrays. CS10001: Programming & Data Structures. Pallab Dasgupta Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #44. Multidimensional Array and pointers

11 'e' 'x' 'e' 'm' 'p' 'l' 'i' 'f' 'i' 'e' 'd' bool equal(const unsigned char pstr[], const char *cstr) {

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #29 Arrays in C

Contents of Lecture 3

C for Java Programmers 1. Last Week. Overview of the differences between C and Java. The C language (keywords, types, functies, etc.

Dynamic memory allocation (malloc)

Heap Arrays and Linked Lists. Steven R. Bagley

Arrays and Pointers in C. Alan L. Cox

Data Representation and Storage

Memory Management. CSC215 Lecture

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

CSE 220: Systems Programming

Unit IV & V Previous Papers 1 mark Answers

QUIZ. 1. Explain the meaning of the angle brackets in the declaration of v below:

Two Dimensional Arrays

So far, system calls have had easy syntax. Integer, character string, and structure arguments.

Arrays (1A) Young Won Lim 1/27/17

Short Notes of CS201

Applications of Pointers (1A) Young Won Lim 4/11/18

[0569] p 0318 garbage

Intermediate Programming, Spring 2017*

CS201 - Introduction to Programming Glossary By

Arrays. CS10001: Programming & Data Structures. Pallab Dasgupta Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur

Arrays and Pointers. CSE 2031 Fall November 11, 2013

Introduction to Programming Block Tutorial C/C++

Arrays and Memory Management

Fundamental of Programming (C)

Content. In this chapter, you will learn:

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

Applications of Arrays (1A) Young Won Lim 3/15/17

SYSC 2006 C Winter 2012

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

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

CS 61C: Great Ideas in Computer Architecture. Lecture 3: Pointers. Bernhard Boser & Randy Katz

Pointers (1A) Young Won Lim 11/1/17

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

Programming Language B

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

A brief introduction to C programming for Java programmers

ESc101: Pointers and Arrays

Programming. Pointers, Multi-dimensional Arrays and Memory Management

C PROGRAMMING LANGUAGE. POINTERS, ARRAYS, OPERATORS AND LOOP. CAAM 519, CHAPTER5

PDS Class Test 2. Room Sections No of students

(Refer Slide Time: 00:23)

Pointers. Introduction

Declaration. Fundamental Data Types. Modifying the Basic Types. Basic Data Types. All variables must be declared before being used.

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

CS453 Arrays in Java in general

Computer Science & Engineering 150A Problem Solving Using Computers

Lecture06: Pointers 4/1/2013

C for Engineers and Scientists: An Interpretive Approach. Chapter 10: Arrays

Applications of Pointers (1A) Young Won Lim 12/26/17

C Programming Language: C ADTs, 2d Dynamic Allocation. Math 230 Assembly Language Programming (Computer Organization) Thursday Jan 31, 2008

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

Arrays. int Data [8] [0] [1] [2] [3] [4] [5] [6] [7]

Arrays, Pointers and Memory Management

EL2310 Scientific Programming

Transcription:

Pointers and Arrays Part II We will continue with our discussion on the relationship between pointers and arrays, and in particular, discuss how arrays with dynamical length can be created at run-time One-dimensional arrays defined dynamically at run time Consider the case in which you do not know the number of elements that an array in your program will have In other words, the length of the array will be determined at run-time after the program starts execution, and therefore, you do not have the luxury of defining the length of the array at the time you write your program C language provides a powerful way to create arrays of any length at run-time In order to create an array of a given type with any number of elements, you first need to declare a pointer to a variable of that type Let s go over this with an example: say you want to create an integer array of N elements (N to be determined by some input during run time, not at compilation time) You first need to declare an integer pointer: int* m; Next, you need to allocate memory for N integer elements C language standard library provides a function called malloc() that allows one to allocate memory for a given number of bytes Here is the function signature of malloc(): void *malloc(size_t size); What this function signature is saying is that malloc() takes an argument of type size_t and returns a void pointer to the first element of the allocated space Note that the return type is void rather than int or float etc This generic interface allows one to allocate space for any type However, you need to tell C compiler exactly what type you are expecting (We will see an example soon) The size argument tells malloc() how much space is needed Let s say you want to allocate memory for N integers, N to be determined at run time; the size that malloc() needs is N times the size of one integer in memory The size of any type in C language can be found by using the sizeof() operator For instance, if you want to find the size of an integer, then you need to operate sizeof() on int as follows: sizeof(int) 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: malloc(n * sizeof(int)) Note that these N elements occupy consecutive memory locations Now, we need to relate this memory space to the integer pointer variable we declared earlier We want to explicitly state that we meant to create an integer array To do that

we need to cast the void pointer returned by malloc() function to integer pointer as follows: (int*) malloc(n * sizeof(int)) And finally, assign this to the integer variable m as follows: m = (int*) malloc(n * sizeof(int)); See Figure 1 below that summarizes these operations Note that the integer pointer variable m holds the address to the first element allocated by malloc() operator int* m Memory allocated by malloc() Figure 1 Allocating an array at run time Now that we have created an integer array of size N, we can refer to its elements by using array indices For instance: x = (m[0] + m[2] )/ 2; This expression assumes that the size or array m is larger than 3, so that referring to element 2 is meaningful Two-dimensional arrays defined dynamically

One can define arrays of any number of dimensions with variable length by using pointers and malloc() Here we will discuss 2-D arrays as an extension to our discussion in the previous section 2D arrays are somewhat more complicated to define The first thing to keep on mind is that the first index of a 2D array is really a pointer to a row of elements See Figure 2 below for a 2D array of size N by M Say this array variable is named a Then, a[i] will refer to the pointer that holds the address of row i, and a[i][j] will refer to the element at row i and column j 0 1 N-1 0 1 M-1 0 1 M-1 Figure 2 A 2D array of size N X M Here are the steps to allocate a 2D integer array of size N by M: 1 Create an array of integer pointers (see Figure 2; this step corresponds to creating the column of elements on the left) 2 For each integer pointer element of the array created in step 1 create an array of integers and assign the first element of the created integer array to the integer pointer element (Again, see Figure 2; this step corresponds to creating a row of elements from 0 to M-1) Now, let s show these steps programmatically Creating an array of integer pointers is as follows: int** m; // step 1 Note the double * in front of m That means you are declaring a pointer to a pointer Next, we allocate an array of integer pointers:

m = (int**) malloc(n * sizeof(int*)); // step 2 Note that the size of elements we create is the size of an integer pointer, not an integer What malloc() will return is a pointer to a pointer array, so we cast it to (int**) So far we have an array of N integer pointers Now we need to create actual storage for integers We need a total of N*M elements, so int* k = (int*) malloc(n*m*sizeof(int)); // step 3 This will allocate the actual integer storage and assign the space to an integer pointer Elements will have consecutive locations For instance, the last element of the first row will be followed by the first element of the second row in memory Now, we need to assign row pointers to actual storage We do that as follows: 1: for (i= 0; i < n; i++) // step 4 2: { 3: m[i] = k; 4: k = k + M; 5: } Let s go over this loop: the for-loop goes over each row to be assigned; in line 3 we assign the next row s pointer to the consecutive set of elements in memory In line 4 we advance the integer pointer k to point to the next row of elements See Figure 3 Important note: a 2D array is really a 1D array in terms of storage in memory, as you can see in step 3 above to allocate N by M elements We interpret this 1D space as a 2D array by assigning pointers separated by M elements as you can see in Figure 3 Now that we have the 2D array created, we can write statements like: x = m[0][2] * m[3][4] / m[1][2];

0 1 0 M-1 M ((N-1)XM) -1 (N-1)XM (NXM) -1 Figure 3 The schematic representation of a 2D MXN integer array created dynamically Note that the blue cells are the actual integer elements and the salmon-colored cells are the pointers to each row of elements