Pointers and Arrays 1

Similar documents
Pointers. Introduction

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

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

Pointers and File Handling

Arrays in C. Prof. Indranil Sen Gupta Dept. of Computer Science & Engg. Indian Institute of Technology Kharagpur. Basic Concept

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

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

EM108 Software Development for Engineers

CS2351 Data Structures. Lecture 7: A Brief Review of Pointers in C

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

ECE 15B COMPUTER ORGANIZATION

Physics 2660: Fundamentals of Scientific Computing. Lecture 3 Instructor: Prof. Chris Neu

Pointers Part 1. Introduction

One Dimension Arrays 1

C++ ARRAYS POINTERS POINTER ARITHMETIC. Problem Solving with Computers-I

Lecture 2: C Programm

IV Unit Second Part STRUCTURES

CS61C Machine Structures. Lecture 4 C Pointers and Arrays. 1/25/2006 John Wawrzynek. www-inst.eecs.berkeley.edu/~cs61c/

Note: unless otherwise stated, the questions are with reference to the C Programming Language. You may use extra sheets if need be.

CS61C : Machine Structures

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

DECLARAING AND INITIALIZING POINTERS

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

Expressions. Arithmetic expressions. Logical expressions. Assignment expression. n Variables and constants linked with operators

Introduction to Scientific Computing and Problem Solving

Self-referential Structures and Linked List. Programming and Data Structure 1

CS61C : Machine Structures

ESC101N Fundamentals of Computing

Data Representation and Storage

Introduction to C Language (M3-R )

CS 61c: Great Ideas in Computer Architecture

Data Representation and Storage. Some definitions (in C)

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

MYcsvtu Notes LECTURE 34. POINTERS

Multi-Dimensional arrays

Introduction to C. Systems Programming Concepts

Administrivia. Introduction to Computer Systems. Pointers, cont. Pointer example, again POINTERS. Project 2 posted, due October 6

Two Dimensional Arrays

CS61C : Machine Structures

Arrays in C. Rab Nawaz Jadoon DCS. Assistant Professor. Department of Computer Science. COMSATS IIT, Abbottabad Pakistan

3.3 Structures. Department of CSE

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

Operators & Expressions

Computer Science & Engineering 150A Problem Solving Using Computers

Laboratory 2: Programming Basics and Variables. Lecture notes: 1. A quick review of hello_comment.c 2. Some useful information

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

Linked-List Basic Examples. A linked-list is Linear collection of self-referential class objects, called nodes Connected by pointer links

Heap Arrays. Steven R. Bagley

More about BOOLEAN issues

Midterm Examination # 2 Wednesday, March 19, Duration of examination: 75 minutes STUDENT NAME: STUDENT ID NUMBER:

Singly linked lists in C.

Homework #3 CS2255 Fall 2012

Computer System and programming in C

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

Will introduce various operators supported by C language Identify supported operations Present some of terms characterizing operators

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

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

CS61C : Machine Structures

Unit IV & V Previous Papers 1 mark Answers

Review! * follows a pointer to its value! & gets the address of a variable! Pearce, Summer 2010 UCB! ! int x = 1000; Pearce, Summer 2010 UCB!

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

C Programming Review CSC 4320/6320

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

C'Programming' data'separate'from'methods/functions' Low'memory'overhead'compared'to'Java'

HW1 due Monday by 9:30am Assignment online, submission details to come

UNIT - V STRUCTURES AND UNIONS

An array is a collection of data that holds fixed number of values of same type. It is also known as a set. An array is a data type.

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

Name :. Roll No. :... Invigilator s Signature : INTRODUCTION TO PROGRAMMING. Time Allotted : 3 Hours Full Marks : 70

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

CS 61C: Great Ideas in Computer Architecture C Pointers. Instructors: Vladimir Stojanovic & Nicholas Weaver

Example: Pointer Basics

Intermediate Programming, Spring 2017*

Maltepe University Computer Engineering Department. BİL 133 Algoritma ve Programlama. Chapter 8: Arrays and pointers

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

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

Kurt Schmidt. October 30, 2018

Floating-point lab deadline moved until Wednesday Today: characters, strings, scanf Characters, strings, scanf questions clicker questions

Hacking in C. Pointers. Radboud University, Nijmegen, The Netherlands. Spring 2019

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved.

These are reserved words of the C language. For example int, float, if, else, for, while etc.

Variables Data types Variable I/O. C introduction. Variables. Variables 1 / 14

More C Pointer Dangers

Section Notes - Week 1 (9/17)

MCA Semester 1. MC0061 Computer Programming C Language 4 Credits Assignment: Set 1 (40 Marks)

Computers Programming Course 6. Iulian Năstac

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

CSCI 171 Chapter Outlines

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

AMCAT Automata Coding Sample Questions And Answers

Algorithms & Data Structures

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

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

M3-R4: PROGRAMMING AND PROBLEM SOLVING THROUGH C LANGUAGE

C++ for Java Programmers

Pointers as Arguments

Arrays. Returning arrays Pointers Dynamic arrays Smart pointers Vectors

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

UNIT 3 OPERATORS. [Marks- 12]

Transcription:

Pointers and Arrays 1

Pointers and Arrays When an array is declared, The compiler allocates sufficient amount of storage to contain all the elements of the array in contiguous memory locations The base address is the location of the first element (index 0) of the array The compiler also defines the array name as a constant pointer to the first element 2

Example Consider the declaration: int x[5] = {1, 2, 3, 4, 5}; Suppose that each integer requires 4 bytes Compiler allocates a contiguous storage of size 5x4 = 20 bytes Suppose the starting address of that storage is 2500 Element Value Address x[0] 1 2500 x[1] 2 2504 x[2] 3 2508 x[3] 4 2512 x[4] 5 2516 3

Contd. The array name x is the starting address of the array Both x and &x[0] have the value 2500 x is a constant pointer, so cannot be changed X = 3400, x++, x += 2 are all illegal If int *p is declared, then p = x; and p = &x[0]; are equivalent We can access successive values of x by using p++ or p-- to move from one element to another 4

Relationship between p and x: p = &x[0] = 2500 p+1 = &x[1] = 2504 p+2 = &x[2] = 2508 p+3 = &x[3] = 2512 p+4 = &x[4] = 2516 C knows the type of each element in array x, so knows how many bytes to move the pointer to get to the next element In general, *(p+i) gives the value of x[i] 5

Example: function to find average int main() { int x[100], k, n; scanf ( %d, &n); for (k=0; k<n; k++) scanf ( %d, &x[k]); float avg (int array[], int size) { int *p, i, sum = 0; p = array; } printf ( \naverage is %f, avg (x, n)); return 0; } for (i=0; i<size; i++) sum = sum + *(p+i); return ((float) sum / size); 6

The pointer p can be subscripted also just like an array! int main() { int x[100], k, n; scanf ( %d, &n); for (k=0; k<n; k++) scanf ( %d, &x[k]); float avg (int array[], int size) { int *p, i, sum = 0; p = array; } printf ( \naverage is %f, avg (x, n)); return 0; } for (i=0; i<size; i++) sum = sum + p[i]; return ((float) sum / size); 7

Important to remember Pitfall: An array in C does not know its own length, & bounds not checked! Consequence: While traversing the elements of an array (either using [ ] or pointer arithmetic), we can accidentally access off the end of an array (access more elements than what is there in the array) Consequence: We must pass the array and its size to a function which is going to traverse it, or there should be some way of knowing the end based on the values (Ex., a ve value ending a string of +ve values) Accessing arrays out of bound can cause segmentation faults Hard to debug (already seen in lab) Always be careful when traversing arrays in programs 8

Pointers to Structures 9

Pointers to Structures Pointer variables can be defined to store the address of structure variables Example: struct student { int roll; char dept_code[25]; float cgpa; }; struct student *p; 10

Just like other pointers, p does not point to anything by itself after declaration Need to assign the address of a structure to p Can use & operator on a struct student type variable Example: struct student x, *p; scanf( %d%s%f, &x.roll, x.dept_code, &x.cgpa); p = &x; 11

Once p points to a structure variable, the members can be accessed in one of two ways: (*p).roll, (*p).dept_code, (*p).cgpa Note the ( ) around *p p > roll, p > dept_code, p > cgpa The symbol > is called the arrow operator Example: printf( Roll = %d, Dept.= %s, CGPA = %f\n, (*p).roll, (*p).dept_code, (*p).cgpa); printf( Roll = %d, Dept.= %s, CGPA = %f\n, p->roll, p->dept_code, p->cgpa); 12

Pointers and Array of Structures Recall that the name of an array is the address of its 0-th element Also true for the names of arrays of structure variables. Consider the declaration: struct student class[100], *ptr ; 13

The name class represents the address of the 0-th element of the structure array ptr is a pointer to data objects of the type struct student The assignment ptr = class; will assign the address of class[0] to ptr Now ptr->roll is the same as class[0].roll. Same for other members When the pointer ptr is incremented by one (ptr++) : The value of ptr is actually increased by sizeof(struct student) It is made to point to the next record Note that sizeof operator can be applied on any data type 14

A Warning When using structure pointers, be careful of operator precedence Member operator. has higher precedence than * ptr > roll and (*ptr).roll mean the same thing *ptr.roll will lead to error The operator > enjoys the highest priority among operators ++ptr > roll will increment ptr->roll, not ptr (++ptr) > roll will access (ptr + 1)->roll (for example, if you want to print the roll no. of all elements of the class array) 15