Memory, Arrays & Pointers

Similar documents
Computer Programming: Skills & Concepts (CP) Strings

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

Pointers, Arrays, and Strings. CS449 Spring 2016

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

CS 61c: Great Ideas in Computer Architecture

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

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

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

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

SYSC 2006 C Winter String Processing in C. D.L. Bailey, Systems and Computer Engineering, Carleton University

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

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

COMP 2355 Introduction to Systems Programming

Arrays and Pointers (part 1)

CSC209H Lecture 4. Dan Zingaro. January 28, 2015

Introduction to Programming Block Tutorial C/C++

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

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

Pointers (continued), arrays and strings

Multidimension array, array of strings

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

Intermediate Programming, Spring 2017*

Summer May 18, 2010

Arrays, Pointers and Memory Management

Pointers (continued), arrays and strings

DAY 3. CS3600, Northeastern University. Alan Mislove

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

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

Procedural Programming & Fundamentals of Programming

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

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

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

CS107 Handout 08 Spring 2007 April 9, 2007 The Ins and Outs of C Arrays

CS1100 Introduction to Programming

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

Arrays and Pointers in C. Alan L. Cox

Arrays and Pointers (part 1)

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

Fall 2018 Discussion 2: September 3, 2018

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

Arrays Arrays and pointers Loops and performance Array comparison Strings. John Edgar 2

Gabriel Hugh Elkaim Spring CMPE 013/L: C Programming. CMPE 013/L: C Programming

High Performance Programming Programming in C part 1

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

Introduction to Scientific Computing and Problem Solving

Lecture 04 Introduction to pointers

Systems Programming and Computer Architecture ( )

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

EL2310 Scientific Programming

Arrays and Pointers. Overview. Arrays Introducing Pointers C-Style Character Strings Multidimensioned Arrays

Dynamic arrays / C Strings

Lectures 5-6: Introduction to C

Dynamic Allocation in C

Contents of Lecture 3

Lecture07: Strings, Variable Scope, Memory Model 4/8/2013

Dynamic Allocation in C

by Pearson Education, Inc. All Rights Reserved.

Today s lecture. Continue exploring C-strings. Pointer mechanics. C arrays. Under the hood: sequence of chars w/ terminating null

Arrays and Strings. CS449 Fall 2017

ECE 15B COMPUTER ORGANIZATION

C: Arrays, and strings. Department of Computer Science College of Engineering Boise State University. September 11, /16

QUIZ. What is wrong with this code that uses default arguments?

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

Arrays and Pointers. CSE 2031 Fall November 11, 2013

CS61C : Machine Structures

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

CS 11 C track: lecture 5

A brief introduction to C programming for Java programmers

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

Pointers, Dynamic Data, and Reference Types

Chapter 2. Procedural Programming

CS 2461: Computer Architecture I

Principles of C and Memory Management

Reading Assignment. Strings. K.N. King Chapter 13. K.N. King Sections 23.4, Supplementary reading. Harbison & Steele Chapter 12, 13, 14

Pointer Arithmetic and Lexical Scoping. CS449 Spring 2016

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

SYSC 2006 C Winter 2012

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

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

EM108 Software Development for Engineers

CS 222: Pointers and Manual Memory Management

Converting a Lowercase Letter Character to Uppercase (Or Vice Versa)

CS201- Introduction to Programming Latest Solved Mcqs from Midterm Papers May 07,2011. MIDTERM EXAMINATION Spring 2010

Create a Program in C (Last Class)

Pointers and Functions Passing Pointers to Functions CMPE-013/L. Pointers and Functions. Pointers and Functions Passing Pointers to Functions

CS 137 Part 6. ASCII, Characters, Strings and Unicode. November 3rd, 2017

Memory and Addresses. Pointers in C. Memory is just a sequence of byte-sized storage devices.

Lectures 5-6: Introduction to C

8. Characters, Strings and Files

CSE2301. Arrays. Arrays. Arrays and Pointers

Exercise 3 / Ch.7. Given the following array, write code to initialize all the elements to 0: int ed[100]; Hint: It can be done two different ways!

Programming in C. Session 7. Seema Sirpal Delhi University Computer Centre

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

Programming. Pointers, Multi-dimensional Arrays and Memory Management

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

CS61C Machine Structures. Lecture 4 C Structs & Memory Management. 9/5/2007 John Wawrzynek. www-inst.eecs.berkeley.edu/~cs61c/

PROGRAMMAZIONE I A.A. 2017/2018

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

PRINCIPLES OF OPERATING SYSTEMS

Transcription:

1 Memory, Arrays & Pointers

Memory int main() { char c; int i,j; double x; c i j x 2

Arrays Defines a block of consecutive cells int main() { int i; int a[3]; i a[0] a[1] a[2]

Arrays - the [ ] operator int arr[5] = { 1, 5, 2, 1,3 address 40*/ }; /*arr begins at 1 5 2 1 3 40 44 48 52 56 60 Address Computation Examples: 1. arr[0] 40+0*sizeof(int) = 40 2. arr[3] 40+3*sizeof(int) = 52 3. arr[i] 40+i*sizeof(int) = 40 + 4*i 4. arr[-1] 40+(-1)*sizeof (int) = 36 // can be the code // segment or other variables 4

Arrays C does not provide any run time checks int a[4]; a[-1] = 0; a[4] = 0; This will compile and run (no errors?!) but can lead to unpredictable results. It is the programmer s responsibility to check whether the index is out of bounds 5

Arrays C does not provide array operations: int a[4]; int b[4]; a = b; // illegal if( a == b ) // legal. ==0, address comparison. 6

Arrays a[i] is just translated to (*(a+i)), thus this code will compile and run fine int a[4]; 0[a]= 42;// first element of array is 42 1[a]= -1;// second element of array is -1 7

Array Initialization // Works, but IMHO in some cases, bad style int arr[3] = {3, 4, 5}; // Good (robust to changes) int arr[] = {3, 4, 5}; // Bad style - Init all items to 0 takes O(n) int arr[3] = {0}; 8 // Bad style - The last is 0 int arr[4] = {3, 4, 5};

Array Initialization // Does not compile int arr[2] = {3, 4, 5}; // Does not compile - array assignment // only in initialization int arr[3]; arr = {2,5,7}; 9

Array Initialization multidimensional (more on this later) // Good, works same as arr[2][3] int arr[][3] = {{2,5,7},{4,6,7}}; // Bad style, but same as above int arr[2][3] = {2,5,7,4,6,7}; // Does not compile int arr[3][2] = {{2,5,7},{4,6,7}}; 10

Pointers Data type for addresses (almost) all you need to know is: & *

Pointers Declaration <type> *p; <type>* p; Both, p points to objects of type <type> Pointer value *p = x; y = *p; *p refers to the object p points to Value pointer &x - the pointer to x(x s address) 12

Pointers - 64 bit! int main() { int i,j; int *x; // x points to an integer i = 1; x = &i; j = *x; x = &j; (*x) = 3; i j x???????????????? 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 13

Pointers - 64 bit! int main() { int i,j; int *x; // x points to an integer i = 1; x = &i; j = *x; x = &j; (*x) = 3; i j x 1 0 0 0???????????? 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 14

Pointers - 64 bit! int main() { int i,j; int *x; // x points to an integer i = 1; x = &i; j = *x; x = &j; (*x) = 3; Little Endian i j x 1 0 0 0???????????? 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 15

Pointers - 64 bit! int main() { int i,j; int *x; // x points to an integer i = 1; x = &i; j = *x; x = &j; (*x) = 3; i j x 1 0 0 0???? 0 0 0 0 0 0 0 0 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 16

Pointers - 64 bit! int main() { int i,j; int *x; // x points to an integer i = 1; x = &i; j = *x; x = &j; (*x) = 3; i j x 1 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 17

Pointers - 64 bit! int main() { int i,j; int *x; // x points to an integer i = 1; x = &i; j = *x; x = &j; (*x) = 3; i j x 1 0 0 0 1 0 0 0 4 0 0 0 0 0 0 0 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 18

Pointers - 64 bit! int main() { int i,j; int *x; // x points to an integer i = 1; x = &i; j = *x; x = &j; (*x) = 3; i j x 1 0 0 0 3 0 0 0 4 0 0 0 0 0 0 0 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19

Example the swap function Does nothing void swap(int a, int b) { int temp = a; a = b; b = temp; } int main() { int x, y; x = 3; y = 7; swap(x, y); // now x==3, y==7 Works void swap(int *pa, int *pb) { int temp = *pa; *pa = *pb; *pb = temp; } int main() { int x, y; x = 3; y = 7; swap(&x, &y); // x == 7, y == 3 20

Pointers & Arrays int *p; int a[3]; p = &a[0]; // same as p = a *(p+1) = 1; // assignment to a[1]! P a[0] a[1] a[2] 8 0 0 0 0 0 0 0 1 0 0 0 21

Pointers & Arrays Arrays are can sometimes be treated as address of the first member. int *p; int a[4]; p = a; // same as p = &a[0]; p[1] = 102; // same as *(p+1)=102; *(a+1) = 102; // same as prev. line p++; // p == a+1 == &a[1] a = p; // illegal a++; // illegal 22

Pointers & Arrays But: int *p; int a[4]; sizeof (p) == sizeof (void*) sizeof (a) == 4 * sizeof (int) Size of the array is known in compile time 23

Pointers & Arrays int main() { int arr[] = {1,3,5,4}; int sum = 0; size_t i; for (i=0; i<sizeof(arr)/sizeof(arr[0]); ++i) { sum += arr[i]; } } 24

25 size_t

size_t an unsigned data type, defined in stddef.h It can be imported by inclusion of stdlib.h (as this file includes stddef.h) This type is used to represent the size of an object. Library functions that take or return sizes expect them to be of type or have the return type of size_t 26 The most frequently used compiler-based operator sizeof should evaluate to a constant value that is compatible with size_t

size_t size_t is a type guaranteed to hold any array index. Use size_t indices and not int. Why? 1. Because it tells the story better 2. Because the C standard uses it (you will get warnings against int) 3. Because int range might be too small for large arrays Danger: You cannot test that a variable of an unsigned type is smaller than 0, because it never happens! 27

size_t Danger: You cannot test that a variable of an unsigned type is smaller than 0, because it never happens! Instead make sure that it doen t happen For example: use the arrow operator : for (size_t i=arr_size-1; i-- > 0;) { arr[i] =...; 28

ptrdiff_t ptrdiff_t is the signed integer type of the result of subtracting two pointers More info: http://en.cppreference.com/w/c/types/ptrdiff_t 29

30 Pointers & Arrays

Pointers & Arrays int foo( int *p ); and int foo( int a[] ); Are declaring the same interface. In both cases, a pointer to int is being passed to the function foo 31

Pointers & Arrays int foo( int *p ); and int foo( int a[3] ); Are declaring the same interface. In both cases, a pointer to int is being passed to the function foo 32

Pointers & Arrays int sum (int arr[]) { size_t i; int sum = 0; for (i=0; i<sizeof(arr)/sizeof(arr[0]); ++i) { sum += arr[i]; } return sum; } // error: sizeof (arr) = sizeof (void*) int* arr[]! arr[n] 33

Pointers & Arrays int sum (int arr[42]) { size_t i; int sum = 0; for (i=0; i<sizeof(arr)/sizeof(arr[0]); ++i) { sum += arr[i]; } return sum; } // error: sizeof (arr) = sizeof (void*) int* arr[]! arr[n] 34

Pointers & Arrays int sum (int arr[], size_t n) { size_t i; int sum = 0; for (i=0; i<n; ++i) { sum += arr[i]; // = arr+ i*sizeof(int) } } return sum; Array size must be passed as a parameter 35

Pointer Arithmetic int a[3]; int *p = a; char *q = (char *)a; // Explicit cast // p and q point to the same location p++; // increment p by 1 int (4 bytes) q++; // increment q by 1 char (1 byte) a[0] a[1] a[2] a[3] q P 36

Pointer Arithmetic int FindFirstNonZero( int a[], size_t n ) { int *p= a; while( (p<a+n) && ((*p) == 0) ) ++p; return p-a; } Same as 37 int FindFirstNonZero( int a[], size_t n ) { int i= 0; while( (i<n) && (a[i] == 0) ) ++i; return i; } Preferable

Pointer Arithmetic int a[4]; int *p= a; long i= (long)a; long j= (long)(a+1); // add 1*sizeof(int) to a; long dif= (long)(j-i); // dif= sizeof(int) Be careful: Pointer arithmetic works just with pointers 38

void * void* p defines a pointer to undetermined type int j; int* p= &j; void* q= p; // no cast needed p = (int*)q ; // cast is needed 39

void * void* address jumps in bytes (like char*) We cannot access to the content of the pointer int j; void *p = &j; int k = *p; // illegal int k = (int)*p ; // still illegal int k = *(int*)p; // legal 40

NULL pointer Special value: points to nothing (defined in stdlib.h, usually as 0 of type void*): int *p = NULL; if( p!= NULL ) { } 41

NULL pointer int *p = NULL; *p = 1; Will compile but will lead to runtime error 42

Pointers to pointers Pointer is a variable type, it also has an address: int main() { int n = 17; int *p = &n; int **p2 = &p; printf("the address of p2 is %p \n",&p2); printf("the address of p is %p \n",p2); printf("the address of n is %p \n",*p2); printf("the value of n is %d \n",**p2); return 0; } 43

44 const

C s const C s const is a qualifier that can be applied to the declaration of any variable to specify its value will not be changed.

C s const Examples: const double E = 2.71828; E= 3.14; // compile error! const int arr[] = {1,2}; arr[0] = 1; // compile error!

C s const C s const can be cast away const int arr[] = {1,2}; int* arr_ptr = (int*)arr; arr_ptr[0] = 3; // compile ok! // but might give a run-time error Helps to find errors. Doesn't protect from evil changes!

Const and Pointer s Syntax Const protects his left side, unless there is nothing to his left and only then it protects his right side (examples next slide).

Const and Pointer s Syntax // Both, cannot change the int pointed by p // using p const int * p = arr; int const * p = arr; // Cannot change the address stored in p int * const p = arr; // Cannot change the address stored in p // and the int pointed by p using p int const * const p = arr;

Const and Pointer s Syntax // Both, cannot change the int pointed by p // using p const int * p = arr; int const * p = arr; // Cannot change the address stored in p int * const p = arr; // Cannot change the address stored in p // and the int pointed by p using p int const * const p = arr; Very Useful Never saw it being used

C s const Do not confuse what the const declaration protects! A pointer to a const variable: int arr[] = {1,2,3}; int const * p = arr; p[1] = 1; // illegal! ptr `` value *(p+1) = 1; // illegal! p = NULL; // legal A const pointer to a variable: int arr[] = {1,2,3}; int* const const_p = arr; const_p[1] = 0; // legal! ptr `` value const_p = NULL; // illegal!

C s const How about arr itself? int arr[] = {1,2,3}; int* const const_p = arr; const_p[1] = 0; // legal! const_p = NULL; // illegal! int *p; arr=p; // compile error!

Const and User Defined Types typedef struct Complex { int _real, _img; int *_imgp; } Complex; Complex const COMP1 = comp2; // ok, init. using comp2 Complex const COMP3 = {3,2,&someInt}; // ok, copying values COMP1._img = 3; // illegal! COMP3._imgP = &someotherint; // illegal! *(COMP3._imgP) = 5; // legal! All the members of a const variable are immutable!

Compare to Java s final All (methods as well as data ) are Class members. final int LIMIT = 10; LIMIT = 11; // illegal! final MyObject obj1 = new MyObject(); MyObject obj2 = null; MyObject obj3 = new MyObject(); obj2 = obj1; // fine, both point now to the same object obj1 = obj3; // illegal! obj1.setsomevalue(5); // legal! final makes primitive types constants and references to objects constant. The values inside the referred final objects are not necessarily constant!

Const Usage The const declaration can (and should!) be used in the definition of a function s arguments, to indicate it would not change them: size_t strlen(const char []); Why use? (This is not a recommendation but a must) clearer code avoids errors part of the interfaces you define! can be used with const objects More of const meaning and usage in C++

C strings manipulation #include <string.h> strcmp strcpy strlen http://www.cplusplus.com/referenc e/cstring/ 56

57 C Strings

Strings Java: C: Char: is 2 bytes (Unicode) String: an object which behaves as a primitive type (an immutable object, passed by value) char: usually 1 byte. An Integer. string: an array of characters. char* txt1 = "text"; char txt2[] = "text"; char txt3[] = { t, e, x, t, \0 }; Addr. ` ` t e x t 58

C Strings Strings are always terminated by a null character, (a character with integer value 0). char* text = "string"; // means text[5] = g and text[6] = \0 // 7 chars are allocated! There is no way to enforce it automatically when you create your own strings, so: remember it s there allocate memory for it specify it when you initialize char by char 59

C string literals ("") When working with char*, C string literals ("") are written in the code segment (part) of the memory. Thus, you can't change them!

C string literals ("") When working with char*, C string literals ("") are written in the code segment (part) of the memory. Thus, you can't change them! char* msg = "text"; msg[0] = w ; // seg fault! error caught only in runtime! msg Stack Addr. `` Code part of memory t e x t OS is protecting this area!

C string literals ("") with const So, what we do is: const char* msg = "text"; msg[0] = t ; // compile error! // better! msg Stack Addr. `` Code part of memory t e x t OS is protecting this area!

Difference between initialzing a pointer and an array with C string literals ("") char* msg = "text"; // msg is a pointer that points to a memory that is in the code part msg Stack Addr. `` Code part of memory char msg2[] = "text"; // msg2 is an array of chars that are on the stack t e x t Stack t e x t \0

Difference between initialzing a pointer and an array with C string literals ("") char* msg = "text"; msg[0]= 'n'; // seg fault - trying to change what is written in the code part of the memory char msg2[] = "text"; msg2[0]= 'n'; // ok - changing what is written in the stack part of the memory

C Strings Examples char txt1[] = "text"; char* txt2 = "text"; int i = strlen(txt1); // i = 4, same for strlen(txt2) txt1[0] = n ; *txt2 = n ; txt2 = txt1; txt1 = txt2; // now txt1="next // illegal! text is in the code // segment // legal. now txt2 points to the // same string. // illegal! if (! (strcmp(txt2,"next")) //This condition is now true {... 65

C Strings Manipulation To manipulate a single character use the functions defined in ctype.h #include <ctype.h> char c = A ; isalpha(c); isupper(c); islower(c); Manipulation of Strings is done by including the string.h header file // copy a string char* strcpy(char * dest, const char* src); // append a string char* strcat(char * dest, const char* src); 66

C Strings Manipulation (2) // compare two strings. // when str1 < str2 lexicographically return < 0 // when str1 > str2 lexicographically return > 0 // when identical return 0 int strcmp(const char * str1, const char* str2); // return strings length, not including the \0!! size_t strlen(const char * str); // Other functions: strncpy(),strncat(),strncmp() 67 NOTE : All C library functions assumes the usages of \0 and enough storage space. No boundary checks! You are responsible. http://www.cplusplus.com/reference/cstring/

C Strings Functions An array version of strcpy(): void strcpy(char * dest, const char* src) { size_t i = 0; while ((dest[i] = src[i])!= '\0')) i++; } 68

C Strings Functions A pointers version of strcpy(): void strcpy(char * dest, const char* src) { while ((*dest = *src)!= '\0')) { dest++; src++; } } 69

C Strings Functions (2) A shorter version:: void strcpy(char * dest,const char* src) { while ((*dest++ = *src++)!= '\0')); } Actually the comparison against \0 is redundant: void strcpy(char * dest,const char* src) { while (*dest++ = *src++); } 70 Style note: Unlike K&R book, we do NOT encourage you to write such code. However, you should be able to read and understand it.