1 Memory, Arrays & Pointers. Memory 2 int main() { char c; int i,j; double x; cijx.

Slides:



Advertisements
Similar presentations
Lectures 10 & 11.
Advertisements

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.
Pointer applications. Arrays and pointers Name of an array is a pointer constant to the first element whose value cannot be changed Address and name refer.
Kernighan/Ritchie: Kelley/Pohl:
Introduction to C Programming in Unix Environment - II Abed Asi Extended System Programming Laboratory (ESPL) CS BGU Fall 2014/2015 Some slides.
Pointers Typedef Pointer Arithmetic Pointers and Arrays.
1 Pointers A pointer variable holds an address We may add or subtract an integer to get a different address. Adding an integer k to a pointer p with base.
ECE 353: Lab C Pointers and Structs. Basics A pointer holds an address to some variable Notation: – Dereferencing operator: * int *x is a declaration.
6/10/2015C++ for Java Programmers1 Pointers and References Timothy Budd.
Pointers Discussion 5 Section Housekeeping HW 1 Issues Array Issues Exam 1 Questions? Submitting on Time!
Chapter 10.
. Plab – Tirgul 2 Const, C Strings. Pointers int main() { int i,j; int *x; // x points to an integer i = 1; x = &i; j = *x; ijx 1.
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.
. Compilation / Pointers Debugging 101. Compilation in C/C++ hello.c Preprocessor Compiler stdio.h tmpXQ.i (C code) hello.o (object file)
Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.
Declaring Arrays Declare an array of 10 elements: int nums[10]; Best practice: #define SIZE 10 int nums[SIZE]; // cannot be int[SIZE] nums; C99: int nums[someVariable]
CS 61C L4 Structs (1) A Carle, Summer 2005 © UCB inst.eecs.berkeley.edu/~cs61c/su05 CS61C : Machine Structures Lecture #4: Strings & Structs
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
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
CS 61C L03 C Arrays (1) A Carle, Summer 2006 © UCB inst.eecs.berkeley.edu/~cs61c/ CS61C : Machine Structures Lecture #3: C Pointers & Arrays
Programming Pointers. Variables in Memory x i c The compiler determines where variables are placed in memory This placement cannot.
Arrays and Pointers in C Alan L. Cox
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
CS 11 C track: lecture 5 Last week: pointers This week: Pointer arithmetic Arrays and pointers Dynamic memory allocation The stack and the heap.
C Programming Tutorial – Part I CS Introduction to Operating Systems.
17. ADVANCED USES OF POINTERS. Dynamic Storage Allocation Many programs require dynamic storage allocation: the ability to allocate storage as needed.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Tevfik Bultan Lecture 12: Pointers continued, C strings.
1 C - Memory Simple Types Arrays Pointers Pointer to Pointer Multi-dimensional Arrays Dynamic Memory Allocation.
Chapter 0.2 – Pointers and Memory. Type Specifiers  const  may be initialised but not used in any subsequent assignment  common and useful  volatile.
Computer Science and Software Engineering University of Wisconsin - Platteville 2. Pointer Yan Shi CS/SE2630 Lecture Notes.
Pointers. The structure of memory Computer memory is a linear sequence of addressable locations Addresses are numbered starting at zero In personal computers,
ECE 103 Engineering Programming Chapter 47 Dynamic Memory Alocation Herbert G. Mayer, PSU CS Status 6/4/2014 Initial content copied verbatim from ECE 103.
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.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures 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.
Lecture 6 C++ Programming Arne Kutzner Hanyang University / Seoul Korea.
1 Homework HW4 due today HW5 is on-line Starting K&R Chapter 5 –Skipping sections for now –Not covering section 5.12.
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.
General comments [1]  array is a fixed sized group in which the elements are of the same type  The general form of array's definition is as follows:
Chapter 8 Characters and Strings. Objectives In this chapter, you will learn: –To be able to use the functions of the character handling library ( ctype).
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.
1 Pointers: Parameter Passing and Return. 2 Passing Pointers to a Function Pointers are often passed to a function as arguments  Allows data items within.
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.
19-Feb-02 Sudeshna Sarkar, CSE, IIT Kharagpur1 Arrays, Pointers, Strings Lecture 18 19/2/2002.
Strings. String Literals String literals are enclosed in double quotes: "Put a disk in drive A, then press any key to continue\n“ A string literal may.
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
1 Memory, Arrays & Pointers. Memory 2 int main() { char c; int i,j; double x; cijx.
Arrays and Pointers (part 1) CSE 2031 Fall July 2016.
Dynamic Allocation in C
Computer Organization and Design Pointers, Arrays and Strings in C
Pointers & Arrays 1-d arrays & pointers 2-d arrays & pointers.
C Programming Tutorial – Part I
C Basics.
Arrays in C.
Lecture 6 C++ Programming
Object Oriented Programming COP3330 / CGS5409
Arrays and Pointers Reference: Chapter , 4.11 CMSC 202.
Chapter 16 Pointers and Arrays
Homework Starting K&R Chapter 5 Good tutorial on pointers
C++ Pointers and Strings
C++ Pointers and Strings
Memory, Arrays & Pointers
Presentation transcript:

1 Memory, Arrays & Pointers

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

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

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

Arrays 5 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…

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 8 // 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}; // Bad style - The last is 0 int arr[4] = {3, 4, 5};

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

Array Initialization – multidimensional (more on this later) 10 // 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}; // Bad int arr[3][2] = {{2,5,7},{4,6,7}};

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

Pointers Declaration *p; * p; Both, p points to objects of 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; ???????????????? ijx

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; 1000???????????? ijx

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; 1000???????????? ijx Little Endian

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; 1000???? ijx

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

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

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

Example – the swap function Does nothingWorks 20 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 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

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

Pointers & Arrays 22 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

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

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

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 25

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 26

Pointers & Arrays 27 int sum (int arr[]) { int i, 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]

Pointers & Arrays 28 int sum (int arr[42]) { int i, 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]

Pointers & Arrays 29 int sum (int arr[], int n) { int i, 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

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[2]a[3]a[0]a[1] qP 30

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

Pointer Arithmetic 32 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

void * 33 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

void * 34 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

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

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

Pointers to pointers 37 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; }

38 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 = ; 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 Helps to find errors. Doesn't protect from evil changes ! const int arr[] = {1,2}; int* arr_ptr = (int*)arr; arr_ptr[0] = 3; // compile ok! // but might give a run-time error const int arr[] = {1,2}; int* arr_ptr = (int*)arr; arr_ptr[0] = 3; // compile ok! // but might give a run-time error

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; // 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; // 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: A const pointer to a variable: ptr value `` ptr value `` int arr[] = {1,2,3}; int const * p = arr; p[1] = 1;// illegal! *(p+1) = 1;// illegal! p = NULL;// legal int arr[] = {1,2,3}; int* const const_p = arr; const_p[1] = 0;// legal! 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! 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 All the members of a const variable are immutable! 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! 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!

Compare to Java’s “final” All (methods as well as data ) are Class members. “final” makes primitive types constants and references to objects constant. The values inside the referred final objects are not necessarily constant ! 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 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!

“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: 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++ int strlen(const char []);

C strings manipulation 50 #include strcmp strcpy strlen … e/cstring/

51 C Strings

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

C Strings Strings are always terminated by a null character, (a character with integer value 0). 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 char* text = "string"; // means text[5] = g and text[6] = \0 // 7 chars are allocated! char* text = "string"; // means text[5] = g and text[6] = \0 // 7 chars are allocated! 53

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 ! char* msg = "text"; msg[0] = ‘w’; // seg fault! – error caught only in runtime ! txet `` Code part of memory Addr. msg Stack 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! const char* msg = "text"; msg[0] = ‘t’;// compile error! // better! txet `` Code part of memory Addr. msg Stack 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 char msg2[] = "text"; // msg2 is an array of chars that are on the stack t e x t \0 txet `` Code part of memory Addr. msg Stack

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 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 Difference between initialzing a pointer and an array with C string literals ( "" )

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

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

C Strings Manipulation (2) NOTE : All C library functions assumes the usages of ‘\0’ and enough storage space. No boundary checks! You are responsible. // compare two strings. // 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() … // compare two strings. // 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() … 61

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

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

C Strings Functions (2) A shorter version:: Actually the comparison against \0 is redundant: 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. void strcpy(char * dest,const char* src) { while ((*dest++ = *src++)!= '\0')); } void strcpy(char * dest,const char* src) { while (*dest++ = *src++); } void strcpy(char * dest,const char* src) { while (*dest++ = *src++); } 64