Arrays and Pointers in C Alan L. Cox

Slides:



Advertisements
Similar presentations
1 Chapter 10 Strings and Pointers. 2 Introduction  String Constant  Example: printf(“Hello”); “Hello” : a string constant oA string constant is a series.
Advertisements

This Time Pointers (declaration and operations) Passing Pointers to Functions Const Pointers Bubble Sort Using Pass-by-Reference Pointer Arithmetic Arrays.
Kernighan/Ritchie: Kelley/Pohl:
Pointers Typedef Pointer Arithmetic Pointers and Arrays.
Pointers Discussion 5 Section Housekeeping HW 1 Issues Array Issues Exam 1 Questions? Submitting on Time!
Memory Arrangement Memory is arrange in a sequence of addressable units (usually bytes) –sizeof( ) return the number of units it takes to store a type.
Pointer. Warning! Dangerous Curves C (and C++) have just about the most powerful, flexible and dangerous pointers in the world. –Most other languages.
1 Fundamental Data Types. 2 Declaration All variables must be declared before being used. –Tells the compiler to set aside an appropriate amount of space.
Pointers. Topics Pointers Pointer Arithmetic Pointers and Arrays.
CS 61C L4 Structs (1) A Carle, Summer 2005 © UCB inst.eecs.berkeley.edu/~cs61c/su05 CS61C : Machine Structures Lecture #4: Strings & Structs
Pointers and Arrays C and Data Structures Baojian Hua
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
Adapted from Dr. Craig Chase, The University of Texas at Austin.
CS 61C L03 C Arrays (1) A Carle, Summer 2006 © UCB inst.eecs.berkeley.edu/~cs61c/ CS61C : Machine Structures Lecture #3: C Pointers & Arrays
CS61C L4 C Pointers (1) Chae, Summer 2008 © UCB Albert Chae Instructor inst.eecs.berkeley.edu/~cs61c CS61C : Machine Structures Lecture #4 –C Strings,
CS 61C Great Ideas in Computer Architecture Lecture 3: Introduction to C, Part II Instructor: Sagar Karandikar
C Arrays and Pointers In Java, pointers are easy to deal with –In fact, there is little that can go wrong in Java since pointer access is done for you.
Pointers CSE 2451 Rong Shi.
Pointers and Arrays Beyond Chapter Pointers and Arrays What are the real differences? Pointer Holds the address of a variable Can be pointed.
CSC 2400 Computer Systems I Lecture 5 Pointers and Arrays.
0 Chap. 5 Pointers and Arrays 5.3Pointers and Arrays 5.4Address Arithmetic 5.5Character Pointers and Functions 5.6Pointer Arrays; Pointers to Pointers.
CS 61C: Great Ideas in Computer Architecture Introduction to C, Part II Instructors: John Wawrzynek & Vladimir Stojanovic
1 Pointers Arrays have a disadvantage: Their size must be known at compile time. We would like the capability to allocate an array-like object of any needed.
5. Arrays, Pointers and Strings 7 th September IIT Kanpur C Course, Programming club, Fall
Prachi A. Joshi Assistant Professor in CSE DIEMS,Aurangabad Unit 1 : Basic Concepts Pointers and dynamic memory allocation, Algorithm Specification, Data.
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.
C Lab 1 Introduction to C. Basics of C Developed by Dennis Ritchie in the 1970s. Maps very easily to machine instructions. Even allows inline assembly!
CSE 232: C++ memory management Overview of Arrays Arrays are the simplest kind of data structure –One item right after another in memory (“contiguous range”
Pointers *, &, array similarities, functions, sizeof.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
1 Lecture07: Memory Model 5/2/2012 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter Array Basics.
Fall 2004CS-183 Dr. Mark L. Hornick 1 C++ Arrays C++ (like Java) supports the concept of collections – mechanisms to sort and manipulate many instances.
Pointers in C++. Topics Covered  Introduction to Pointers  Pointers and arrays  Character Pointers, Arrays and Strings  Examples.
CS 61C: Great Ideas in Computer Architecture Introduction to C, Part II Instructors: Krste Asanovic & Vladimir Stojanovic
Pointers & References. Pointers Pointer arithmetic Pointers and arrays Pointer-related typedef’s Pointers and const References.
CSE 332: C++ pointers, arrays, and references Overview of Pointers and References Often need to refer to another object –Without making a copy of the object.
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.
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.
1 Homework Continue with K&R Chapter 5 –Skipping sections for now –Not covering section 5.12 Continue on HW5.
Chapter 5 Pointers and Arrays Ku-Yaw Chang Assistant Professor, Department of Computer Science and Information Engineering Da-Yeh.
Pointers: Basics. 2 Address vs. Value Each memory cell has an address associated with it
Windows Programming Lecture 03. Pointers and Arrays.
1 Memory, Arrays & Pointers. Memory 2 int main() { char c; int i,j; double x; cijx.
CS 61C: Great Ideas in Computer Architecture C Pointers Instructors: Vladimir Stojanovic & Nicholas Weaver 1.
Stack and Heap Memory Stack resident variables include:
Computer Organization and Design Pointers, Arrays and Strings in C
The Machine Model Memory
Memory, Data, & Addressing II CSE 351 Autumn 2017
CSE 303 Concepts and Tools for Software Development
CS 61C: Great Ideas in Computer Architecture Lecture 3: Pointers
Lecture 6 C++ Programming
Introduction to Pointers
Fundamental Data Types
Introduction to Pointers
5. Arrays, Pointers and Strings
Review Questions If the word size of a machine is 64-bits, which of the following is usually true? (pick all that apply) 64 bits is the size of a pointer.
Memory, Data, & Addressing II CSE 351 Winter 2018
Memory, Data, & Addressing II CSE 351 Summer 2018
Outline Defining and using Pointers Operations on pointers
Chapter 16 Pointers and Arrays
Pointers and Arrays Beyond Chapter 16
Memory, Data, & Addressing II CSE 351 Winter 2018
Pointers Pointers point to memory locations
Fundamental Data Types
Homework Continue with K&R Chapter 5 Skipping sections for now
Introduction to Pointers
Introduction to C CS 3410.
Presentation transcript:

Arrays and Pointers in C Alan L. Cox

Objectives Be able to use arrays, pointers, and strings in C programs Be able to explain the representation of these data types at the machine level, including their similarities and differences Cox / RixnerArrays and Pointers2

Cox / RixnerArrays and Pointers3 Arrays in C No bounds checking! Allowed – usually causes no error array[10] may overwrite b Unlike Java, array size in declaration int array[10]; int b; array[0] = 3; array[9] = 4; array[10] = 5; array[-1] = 6; Compare: C: int array[10]; Java: int[] array = new int[10]; All elements of same type – homogenous First element (index 0) Last element (index size - 1)

Cox / RixnerArrays and Pointers4 Array Representation Homogeneous  Each element same size – s bytes  An array of m data values is a sequence of ms bytes  Indexing: 0 th value at byte s0, 1 st value at byte s1, … m and s are not part of representation  Unlike in some other languages  s known by compiler – usually irrelevant to programmer  m often known by compiler – if not, must be saved by programmer a[0] a[1] a[2] 0x1000 0x1004 0x1008 int a[3];

Cox / RixnerArrays and Pointers5 Array Representation char c1; int a[3]; char c2; int i; c1 a[0] a[1] a[2] i 0x1000 0x1004 0x1008 0x100C 0x1014 c2 0x1010 Could be optimized by making these adjacent, and reducing padding (by default, not) Array aligned by size of elements

Cox / RixnerArrays and Pointers6 Array Sizes What is sizeof(array[3]) ? sizeof(array) ? int array[10]; 4 40 returns the size of an object in bytes

Cox / RixnerArrays and Pointers7 Multi-Dimensional Arrays int matrix[2][3]; matrix[1][0] = 17; matrix[0][0] matrix[0][1] matrix[0][2] 0x1000 0x1004 0x1008 matrix[1][0] matrix[1][1] matrix[1][2] 0x100C 0x1010 0x1014 Recall: no bounds checking What happens when you write: matrix[0][3] = 42; “Row Major” Organization

Cox / RixnerArrays and Pointers8 Variable-Length Arrays int function(int n) { int array[n]; … New C99 feature: Variable-length arrays defined within functions Global arrays must still have fixed (constant) length

Cox / RixnerArrays and Pointers9 Memory Addresses Storage cells are typically viewed as being byte-sized  Usually the smallest addressable unit of memory Few machines can directly address bits individually  Such addresses are sometimes called byte- addresses Memory is often accessed as words  Usually a word is the largest unit of memory access by a single machine instruction CLEAR’s word size is 8 bytes (= sizeof(long) )  A word-address is simply the byte-address of the word’s first byte

Cox / RixnerArrays and Pointers10 Pointers Special case of bounded-size natural numbers  Maximum memory limited by processor word-size  2 32 bytes = 4GB, 2 64 bytes = 16 exabytes A pointer is just another kind of value  A basic type in C int *ptr; The variable “ptr” is a pointer to an “int”.

Cox / RixnerArrays and Pointers11 Pointer Operations in C Creation & variableReturns variable’s memory address Dereference * pointerReturns contents stored at address Indirect assignment * pointer = valStores value at address Of course, still have... Assignment pointer = ptrStores pointer in another variable

Cox / RixnerArrays and Pointers12 Using Pointers int i1; int i2; int *ptr1; int *ptr2; i1 = 1; i2 = 2; ptr1 = &i1; ptr2 = ptr1; *ptr1 = 3; i2 = *ptr2; i1: i2: ptr1: 0x1000 0x1004 0x1008 … ptr2: … 0x100C 0x1010 0x x

Cox / RixnerArrays and Pointers13 Using Pointers (cont.) Type check warning: int_ptr2 is not an int int1 becomes 8 int int1 = 1036; /* some data to point to */ int int2 = 8; int *int_ptr1 = &int1; /* get addresses of data */ int *int_ptr2 = &int2; *int_ptr1 = int_ptr2; *int_ptr1 = int2; What happens?

Cox / RixnerArrays and Pointers14 Using Pointers (cont.) Type check warning: *int_ptr2 is not an int * Changes int_ptr1 – doesn’t change int1 int int1 = 1036; /* some data to point to */ int int2 = 8; int *int_ptr1 = &int1; /* get addresses of data */ int *int_ptr2 = &int2; int_ptr1 = *int_ptr2; int_ptr1 = int_ptr2; What happens?

Cox / RixnerArrays and Pointers15 Pointer Arithmetic pointer + numberpointer – number E.g., pointer + 1 adds 1 something to a pointer char *p; char a; char b; p = &a; p += 1; int *p; int a; int b; p = &a; p += 1; In each, p now points to b (Assuming compiler doesn’t reorder variables in memory) Adds 1*sizeof(char) to the memory address Adds 1*sizeof(int) to the memory address Pointer arithmetic should be used cautiously

Cox / RixnerArrays and Pointers16 The Simplest Pointer in C Special constant pointer NULL  Points to no data  Dereferencing illegal – causes segmentation fault  To define, include or

Cox / RixnerArrays and Pointers17 Generic Pointers void *: a “pointer to anything” Lose all information about what type of thing is pointed to  Reduces effectiveness of compiler’s type-checking  Can’t use pointer arithmetic void *p; int i; char c; p = &i; p = &c; putchar(*(char *)p); type cast: tells the compiler to “change” an object’s type (for type checking purposes – does not modify the object in any way) Dangerous! Sometimes necessary…

Cox / RixnerArrays and Pointers18 Pass-by-Reference void set_x_and_y(int *x, int *y) { *x = 1001; *y = 1002; } void f(void) { int a = 1; int b = 2; set_x_and_y(&a,&b); } 1 2 a b x y

Cox / RixnerArrays and Pointers19 Arrays and Pointers Dirty “secret”: Array name  a pointer to the initial (0th) array element a[i]  *(a+i) An array is passed to a function as a pointer  The array size is lost! Usually bad style to interchange arrays and pointers  Avoid pointer arithmetic! Really int *array int foo(int array[], unsigned int size) { … array[size - 1] … } int main(void) { int a[10], b[5]; … foo(a, 10)… foo(b, 5) … } Must explicitly pass the size Passing arrays:

Cox / RixnerArrays and Pointers20 Arrays and Pointers int foo(int array[], unsigned int size) { … printf(“%d\n”, sizeof(array)); } int main(void) { int a[10], b[5]; … foo(a, 10)… foo(b, 5) … printf(“%d\n”, sizeof(a)); } What does this print? because array is really a pointer

Cox / RixnerArrays and Pointers21 Arrays and Pointers int i; int array[10]; for (i = 0; i < 10; i++) { array[i] = …; } int *p; int array[10]; for (p = array; p < &array[10]; p++) { *p = …; } These two blocks of code are functionally equivalent

Cox / RixnerArrays and Pointers22 Strings In C, strings are just an array of characters  Terminated with ‘\0’ character  Arrays for bounded-length strings  Pointer for constant strings (or unknown length) char str1[15] = “Hello, world!\n”; char *str2 = “Hello, world!\n”; Hello,wlord!\n length Hello,wlord!\n terminator Pascal, Java, … C, … C terminator: ’\0’

Cox / RixnerArrays and Pointers23 String length Must calculate length: Provided by standard C library: #include int strlen(char str[]) { int len = 0; while (str[len] != ‘\0’) len++; return (len); } can pass an array or pointer Check for terminator array access to pointer! What is the size of the array???

Pointer to Pointer (char **argv) Cox / RixnerArrays and Pointers24 Passing arguments to main: int main(int argc, char **argv) {... } an array/vector of char * Recall when passing an array, a pointer to the first element is passed size of the argv array/vector Suppose you run the program this way UNIX%./program hello argc == 5 (five strings on the command line )

Cox / RixnerArrays and Pointers25 char **argv argv[0] argv[1] argv[2] 0x1000 0x1008 0x1010 argv[3] argv[4] 0x1018 0x1020 “./program” “hello” “1” “2” “3” These are strings!! Not integers!

Cox / RixnerArrays and Pointers26 Next Time Structures and Unions