1 Pointers and Arrays. 2 When an array is declared,  The compiler allocates sufficient amount of storage to contain all the elements of the array in.

Slides:



Advertisements
Similar presentations
Etter/Ingber Arrays and Matrices. Etter/Ingber One-Dimensional Arrays 4 An array is an indexed data structure 4 All variables stored in an array are of.
Advertisements

Incomplete Structs struct B; struct A { struct B * partner; // other declarations… }; struct B { struct A * partner; // other declarations… };
An introduction to pointers in c
Programming and Data Structure
Unions The storage referenced by a union variable can hold data of different types subject to the restriction that at any one time, the storage holds data.
Structures Spring 2013Programming and Data Structure1.
Single Variable and a Lot of Variables The declaration int k; float f; reserve one single integer variable called k and one single floating point variable.
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
1 1-d Arrays. 2 Array Many applications require multiple data items that have common characteristics  In mathematics, we often express such groups of.
Dynamic Memory Allocation
This Time Pointers (declaration and operations) Passing Pointers to Functions Const Pointers Bubble Sort Using Pass-by-Reference Pointer Arithmetic Arrays.
CSCI 171 Presentation 11 Pointers. Pointer Basics.
Kernighan/Ritchie: Kelley/Pohl:
Pointers Typedef Pointer Arithmetic Pointers and Arrays.
ECE 353: Lab C Pointers and Structs. Basics A pointer holds an address to some variable Notation: – Dereferencing operator: * int *x is a declaration.
Pointers Discussion 5 Section Housekeeping HW 1 Issues Array Issues Exam 1 Questions? Submitting on Time!
Pointers. Topics Pointers Pointer Arithmetic Pointers and Arrays.
ARRAYS AND POINTERS Although pointer types are not integer types, some integer arithmetic operators can be applied to pointers. The affect of this arithmetic.
CS 61C L03 C Arrays (1) A Carle, Summer 2005 © UCB inst.eecs.berkeley.edu/~cs61c/su05 CS61C : Machine Structures Lecture #3: C Pointers & Arrays
CS 61C L03 C Arrays (1) A Carle, Summer 2006 © UCB inst.eecs.berkeley.edu/~cs61c/ CS61C : Machine Structures Lecture #3: C Pointers & Arrays
Pointers CS362. Pointers A Pointer is a variable that can hold a memory address Pointers can be used to: Indirectly reference existing variables (sometimes.
1 1-d Arrays. 2 Array Many applications require multiple data items that have common characteristics  In mathematics, we often express such groups of.
POINTERS. 1.a) POINTER EXPRESSIONS Pointer variables can be used in expression If p1 and p2 are properly declared and initialized pointers then following.
 2007 Pearson Education, Inc. All rights reserved C Pointers.
CSC 2400 Computer Systems I Lecture 5 Pointers and Arrays.
14/3/02 Sudeshna Sarkar, CSE, IIT Kharagpur1 Structures, ADT Lecture 25 14/3/2002.
1 Data Structures CSCI 132, Spring 2014 Lecture 10 Dynamic Memory and Pointers.
1 Pointers and Strings Chapter 5 2 What You Will Learn...  How to use pointers Passing arguments to functions with pointers See relationship of pointers.
Pointers. What is pointer l Everything stored in a computer program has a memory address. This is especially true of variables. char c=‘y’; int i=2; According.
Pointers: Basics. 2 What is a pointer? First of all, it is a variable, just like other variables you studied  So it has type, storage etc. Difference:
Copyright 2005, The Ohio State University 1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation.
CS 161 Introduction to Programming and Problem Solving Chapter 19 Single-Dimensional Arrays Herbert G. Mayer, PSU Status 10/8/2014 Initial content copied.
ICOM 4035 – Data Structures Dr. Manuel Rodríguez Martínez Electrical and Computer Engineering Department Lecture 3 – August 28, 2001.
Data Types Declarations Expressions Data storage C++ Basics.
Integer Types short month; // half of a machine word int car; // one machine word unsigned long distance; Character Types char c = ‘\0’; // one byte char.
Pointers *, &, array similarities, functions, sizeof.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 14: Pointers.
Topic 4: C Data Structures CSE 30: Computer Organization and Systems Programming Winter 2011 Prof. Ryan Kastner Dept. of Computer Science and Engineering.
+ Pointers. + Content Address of operator (&) Pointers Pointers and array.
Computer And Programming Array and Pointer. Array provides a means to allocating and accessing memory. Pointers, on the other hand, provides a way to.
Pointers in C++. Topics Covered  Introduction to Pointers  Pointers and arrays  Character Pointers, Arrays and Strings  Examples.
Variables and memory addresses
EEL 3801 C++ as an Enhancement of C. EEL 3801 – Lotzi Bölöni Comments  Can be done with // at the start of the commented line.  The end-of-line terminates.
Pointers and Arrays An array's name is a constant whose value is the address of the array's first element. For this reason, the value of an array's name.
Pointers PART - 2. Pointers Pointers are variables that contain memory addresses as their values. A variable name directly references a value. A pointer.
1 Recall that... char str [ 8 ]; str is the base address of the array. We say str is a pointer because its value is an address. It is a pointer constant.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT:10 Advance Pointer Array, String and Dynamic Memory Allocation CS2311 Computer Programming.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 11: Pointers.
CS162 - Topic #12 Lecture: –Arrays with Structured Elements defining and using arrays of arrays remember pointer arithmetic Programming Project –Any questions?
Lecture 7: Arrays BJ Furman 06OCT2012. The Plan for Today Announcements Review of variables and memory Arrays  What is an array?  How do you declare.
Chapter 16 Pointers and Arrays Pointers and Arrays We've seen examples of both of these in our LC-3 programs; now we'll see them in C. Pointer Address.
C++ for Engineers and Scientists Second Edition Chapter 12 Pointers.
Pointers: Basics. 2 Address vs. Value Each memory cell has an address associated with it
Windows Programming Lecture 03. Pointers and Arrays.
You learned how to declare pointer variables how to store the address of a variable into a pointer variable of the same type as the variable how to manipulate.
Pointers Pointers are variables that contain memory addresses as their values. A variable directly contains a specific value. A pointer contains an address.
1-d Arrays.
Computer Organization and Design Pointers, Arrays and Strings in C
Hassan Khosravi / Geoffrey Tien
Pointer Data Type and Pointer Variables II
Pointers and References
Dynamic Memory Allocation
Lecture 18 Arrays and Pointer Arithmetic
Dynamic Memory Allocation
Chapter 16 Pointers and Arrays
Data Structures and Algorithms Introduction to Pointers
Pointers and References
Programming and Data Structure
Presentation transcript:

1 Pointers and Arrays

2 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

3 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] x[1] x[2] x[3] x[4]

4 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

5 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]

6 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]); printf (“\nAverage is %f”, avg (x, n)); return 0; } float avg (int array[], int size) { int *p, i, sum = 0; p = array; for (i=0; i<size; i++) sum = sum + *(p+i); return ((float) sum / size); }

7 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]); printf (“\nAverage is %f”, avg (x, n)); return 0; } float avg (int array[], int size) { int *p, i, sum = 0; p = array; for (i=0; i<size; i++) sum = sum + p[i] ; return ((float) sum / size); }

8 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

9 Pointers to Structures

10 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;

11 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;

12 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);

13 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 ;

14 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

15 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)