Arrays and Pointers (part 1)

Similar documents
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.

Arrays, Pointers and Memory Management

CSE2301. Arrays. Arrays. Arrays and Pointers

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

CSE2301. Arrays. Arrays. Arrays and Pointers

Multidimension array, array of strings

Summer May 18, 2010

SYSC 2006 C Winter 2012

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

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

Quick review pointer basics (KR ch )

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

EM108 Software Development for Engineers

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

Course organization. Course introduction ( Week 1)

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

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

CSE2301. Dynamic memory Allocation. malloc() Dynamic Memory Allocation and Structs

Dynamic Memory Allocation

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

Content. In this chapter, you will learn:

Dynamic memory allocation (malloc)

... Lecture 12. Pointers

Pointers. Pointers. Pointers (cont) CS 217

Dynamic Allocation in C

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

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

Lectures 5-6: Introduction to C

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

Structures and Pointers

[0569] p 0318 garbage

Dynamic Allocation in C

Procedural programming with C

Lectures 5-6: Introduction to C

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

Memory, Arrays & Pointers

Week 5 9 April 2018 NWEN 241 More on pointers. Alvin Valera. School of Engineering and Computer Science Victoria University of Wellington

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

Unit IV & V Previous Papers 1 mark Answers

CS 61c: Great Ideas in Computer Architecture

Pointers. Pointer References

CSE 230 Intermediate Programming in C and C++ Arrays, Pointers and Strings

Understanding Pointers

Character Strings. String-copy Example

Arrays. An array is a collection of several elements of the same type. An array variable is declared as array name[size]

MYcsvtu Notes LECTURE 34. POINTERS

Intermediate Programming, Spring 2017*

M4.1-R3: PROGRAMMING AND PROBLEM SOLVING THROUGH C LANGUAGE

Memory Allocation in C

A Shotgun Introduction to C

Computer Programming. C Array is a collection of data belongings to the same data type. data_type array_name[array_size];

Pointers and File Handling

dynamic memory allocation

PDS Class Test 2. Room Sections No of students

POINTERS. Content. Pointers. Benefits of Pointers. In this chapter, you will learn:

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

Chapter 16. Pointers and Arrays. Address vs. Value. Another Need for Addresses

Basic and Practice in Programming Lab7

Variation of Pointers

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

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

Arrays, Strings, and Pointers

Pointer in C SHARDA UNIVERSITY. Presented By: Pushpendra K. Rajput Assistant Professor

Aryan College. Fundamental of C Programming. Unit I: Q1. What will be the value of the following expression? (2017) A + 9

Arrays, Strings, and Pointers

A Shotgun Introduction to C

Chapter 7 C Pointers

Programming. Pointers, Multi-dimensional Arrays and Memory Management

Computer Programming Unit 3

Homework #3 CS2255 Fall 2012

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

K. N. King: chapters 8 and 12

MODULE 5: Pointers, Preprocessor Directives and Data Structures

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

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

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

Introduction to Scientific Computing and Problem Solving

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

CS113: Lecture 9. Topics: Dynamic Allocation. Dynamic Data Structures

Slide Set 3. for ENCM 339 Fall 2017 Section 01. Steve Norman, PhD, PEng

Memory, Data, & Addressing II CSE 351 Spring

Arrays and Pointers in C. Alan L. Cox

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

CS11001/CS11002 Programming and Data Structures (PDS) (Theory: 3-1-0) Introduction to arrays

CSE 230 Intermediate Programming in C and C++ Arrays and Pointers

Programs in memory. The layout of memory is roughly:

C BOOTCAMP DAY 2. CS3600, Northeastern University. Alan Mislove. Slides adapted from Anandha Gopalan s CS132 course at Univ.

Computer Science & Engineering 150A Problem Solving Using Computers

A3-R3: PROGRAMMING AND PROBLEM SOLVING THROUGH 'C' LANGUAGE

Contents. A Review of C language. Visual C Visual C++ 6.0

ONE DIMENSIONAL ARRAYS

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

Practice Sheet #07 with Solutions

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

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

Transcription:

Arrays and Pointers (part 1) CSE 2031 Fall 2012 Arrays Grouping of data of the same type. Loops commonly used for manipulation. Programmers set array sizes explicitly. Arrays: Example Syntax type name[size]; Examples int bigarray[10]; double a[3]; char grade[10], onegrade; October 1, 2012 1 2 3 Arrays: Definition and Access Arrays Stored in Memory Initialization Defining an array: allocates memory int score[5]; Allocates an array of 5 integers named "score" Individual parts can be called: Indexed or subscripted variables "Elements" of the array 1234 1235 1236 1237 1238.. a[0] a[1] a[2] In declarations enclosed in curly braces int a[5] = 11,22; Declares array a and initializes first two elements and all remaining set to zero Value in brackets called index or subscript Numbered from 0 to (size 1) 4 a[n] 1260 1261 Some other variables 5 int b[ ] = 1,2,8,9,5; Declares array b and initializes all elements and sets the length of the array to 5 6 1

Array Access x = ar[2]; ar[3] = 2.7; What is the difference between ar[i]++, ar[i++], ar[++i]? Pointers CSE 2031 Fall 2012 Pointers and Addresses (5.1) Memory address of a variable Declared with data type, * and identifier type *pointer_var1, *pointer_var2, ; Example. double *p; int *p1, *p2; There has to be a * before EACH of the pointer variables 7 8 9 Pointers and Addresses (cont.) Use the "address of" operator (&) General form: pointer_variable = &ordinary_variable Name of the pointer Name of ordinary variable 10 Using a Pointer Variable Can be used to access a value Unary operator * used * pointer_variable In executable statement, indicates value Example int *p1, v1; v1 = 0; p1 = &v1; *p1 = 42; printf( %d\n,v1); printf( %d\n,*p1); Output: 42 42 11 Pointer Example 1 int x,y; int *z; y x = 25; y = x; z = &x; 25 1200-3 1204 7 1208-11 25 1204 9608-11 8404-7 x z 12 2

Pointer Variables Pointer Example 2 int x = 25, *y, z; Pointer Example 3 y = &x; z = 1024; BAD idea z = *y; x Instead, use z = &x 25 1200-3 1204 7 1208-11 y z 1204 25 9608-11 8404-7 13 14 15 More Examples Pointers and Function Arguments (5.2) The Correct Version int x = 1, y = 2, z[10], k; int *ip; ip = &x; /* ip points to x*/ y = *ip; /* y is now 1 */ *ip = 0; /* x is now 0 */ z[0] = 0; ip = &z[0]; /* ip points to z[0] */ for (k = 0; k < 10; k++) z[k] = *ip + k; *ip = *ip + 100; ++*ip; (*ip)++; /* How about *ip++??? */ Write a function that swaps the contents of two integers a and b. void main( ) int a, b; /* Input a and b */ swap(a, b); printf( %d %d, a, b); C passes arguments to functions by values. void swap(int x, int y) int temp; temp = x; x = y; y = temp; void swap(int *px, int *py) int temp; temp = *px; *px = *py; *py = temp; void main( ) int a, b; /* Input a and b */ swap(&a, &b); printf( %d %d, a, b); 16 17 18 3

Pointers and Arrays (5.3) Pointers and Arrays: Example Arrays and Pointers 19 Identifier of an array is equivalent to the address of its first element. int numbers[20]; int *p; p = numbers; numbers = p; // Valid // Invalid p and numbers are equivalent and they have the same properties. Only difference is that we could assign another value to the pointer p whereas numbers will always point to the first of the 20 integer numbers of type int. 20 int a[10]; /* Init a[i] = i */ int *pa; pa = &a[0] x = *pa; /*same as x = a[0]*/ int y, z; y = *(pa + 1); z = *(pa + 2); 21 Pointers and Arrays: More Examples Computing String Lengths Passing Sub-arrays to Functions int a[10], *pa; pa = a; /* same as pa = &a[0]*/ pa++; /*same as pa = &a[1]*/ a[i] *(a+i) &a[i] a+i pa[i] *(pa+i) Notes a = pa; a++; are illegal. Think of a as a constant, not a modifiable variable. p[-1], p[-2], etc. are syntactically legal. /* strlen: return length of string s */ int strlen( char *s ) /* or (char s[]) */ int n; for ( n = 0; *s!= '\0', s++ ) n++; return n; Callers: strlen( "hello, world ); /* string constant */ strlen( array ); /* char array[100]; */ strlen( ptr ); /* char *ptr; pointing to an array */ It is possible to pass part of an array to a function, by passing a pointer to the beginning of the sub-array. my_func( int ar[ ] )... or my_func( int *ar )... my_func(&a[5]) or my_func(a + 5) 22 23 24 4

Arrays Passed to a Function Address Arithmetic (5.4) Address Arithmetic: Example Arrays passed to a function are passed by reference. The name of the array is a pointer to its first element. Example: copy_array( int A[ ], int B[ ] ); The call above does not copy the array in the function call, just a reference to it. 25 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 ) 26 /* strlen: return length of string s */ int strlen(char *s) char *p = s; while (*p!= '\0') p++; return p - s; 27 Address Arithmetic: Summary Character Pointers and Functions (5.5) Important Difference between... 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 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. char *pmessage; pmessage = "now is the time"; assigns to pmessage a pointer to the character array. This is not a string copy; only pointers are involved. C does not provide any operators for processing an entire string of characters as a unit. char amessage[] = "now is the time"; /* an array */ char *pmessage = "now is the time"; /* a pointer */ amessage will always refer to the same storage. pmessage may later be modified to point elsewhere. 28 29 30 5

Example: String Copy Function Dynamic Memory Allocation (7.8.5) /* strcpy: copy t to s; array subscript version */ void strcpy(char *s, char *t) int i; i = 0; while ((s[i] = t[i])!= '\0') i++; /* strcpy: copy t to s; pointer version */ void strcpy(char *s, char *t) int i; i = 0; while ((*s = *t)!= '\0') s++; t++; Dynamic Memory Allocation CSE 2031 Fall 2012 How to allocate memory during run time? int x = 10; int my_array[ x ]; /* not allowed in C */ /* strcpy: copy t to s; pointer version 2 */ void strcpy(char *s, char *t) while ((*s++ = *t++)!= '\0') ; 31 32 33 malloc() calloc() realloc() In stdlib.h void *calloc( int n, int s ); What if we want our array to grow (or shrink)? void *malloc( int n ); Allocates memory at run time. Returns a pointer (to a void) to at least n bytes available. Returns null if the memory was not allocated. The allocated memory is not initialized. Allocates an array of n elements where each element has size s; calloc( ) initializes the allocated memory all to 0. 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. 34 35 36 6

free() Example Next time... void free( void *ptr ) #include<stdio.h> #include<stdlib.h> Structures (Chapter 6) Releases the memory we previously allocated. ptr must have been returned from a previous calloc, malloc, or realloc. C does not do automatic garbage collection. main() int *a, i, n, sum=0; printf( Input an aray size ); scanf( %d, &n ); a = calloc( n, sizeof(int) ); /* a = malloc ( n * sizeof(int) ) */ for( i=0; i<n; i++ ) scanf( %d, &a[i] ); for( i=0; i<n; i++ ) sum += a[i]; free( a ); printf( Number of elelments = %d and the sum is %d\n,n,sum); 37 38 39 7