Introduction to Scientific Computing and Problem Solving
|
|
- Catherine Andrews
- 5 years ago
- Views:
Transcription
1 Introduction to Scientific Computing and Problem Solving Lecture #22 Pointers CS4 - Introduction to Scientific Computing and Problem Solving Announcements HW8 due tomorrow at 2:30pm What s left: Lab 9 & 10, HW9 & Image project CS4 - Introduction to Scientific Computing and Problem Solving
2 This lecture Pointers The true beauty of C Examples - applications CS4 - Introduction to Scientific Computing and Problem Solving Let s C so far Intro Basic types (int, float, double), variables, operations, basic I/O Conditionals & Loops Flow control Arrays Representation, usage/manipulation Functions declaration, definition, usage call by value Vs. call by reference (w/ arrays) CS4 - Introduction to Scientific Computing and Problem Solving
3 3 Recall: Memory Organization The amount of memory needed to store a variable depends on the variable type int 4 bytes double 32 bytes Each memory location contains a byte and has a unique address var1 (int) var2 (int) CS4 - Introduction to Scientific Computing and Problem Solving Recall: Arrays Memory Representation Arrays occupy contiguous blocks of memory int myarray[3]; myarray[0] 1000 total number of bytes = 12 myarray[1] myarray[2] CS4 - Introduction to Scientific Computing and Problem Solving
4 Memory Organization: Closer View On the machine level a computer's main memory is typically divided into bytes A byte is capable of storing eight bits of information, i.e., it can represent 2 8 = 256 different values = 89 Each byte in memory has an associated address Addresses are consecutive numbers that define the address space of a computer CS4 - Introduction to Scientific Computing and Problem Solving Lvalues We have already seen how variables and arrays are represented in memory In general, an expression that can appear on the left side of the assignment operator = is called an Lvalue An Lvalue must refer to a memory location (so far, just names of variables and array elements) char c; short int a[3]; Some other C data types, occupying 1 and resp. 2 bytes (more in next lecture) c a[0] a[1] a[2] CS4 - Introduction to Scientific Computing and Problem Solving
5 What Else Can Be an Lvalue? Pointers Make it possible to return multiple values from a single function call Facilitate working with large data aggregates (e.g., struct, next lecture) Shortcut for array element manipulation Makes things easy and hard CS4 - Introduction to Scientific Computing and Problem Solving Pointers: "Remember the Address" A pointer variable is a variable that can store an address Its value, a pointer, is nothing more than an address in memory The number of bytes needed to store an address depends on the size of the address space For example, a 32-bit address is sufficient for 4 gigabytes (GB) of main memory (2 10 = 1024 = 1 K, 2 32 = 4 * 2 10 * 2 10 * 2 10 ). Graphically, a pointer variable p that points to the address of a variable i is shown as: p i CS4 - Introduction to Scientific Computing and Problem Solving
6 Pointers and Ordinary Variables Ordinary variable holds a data value (int, char, float, struct ) Pointer variable holds a reference to a variable The map leads us points to the treasure CS4 - Introduction to Scientific Computing and Problem Solving Declaring Pointer Variables Like ordinary variables, pointer variables need to be declared before they can be used in C Moreover, C requires that we explicitly describe the type of variable (Lvalue really) that the pointer will refer to - the reference type An asterisk * is used to distinguish a pointer (variable) from regular variables int *p; float *f; /* pointer variable to an integer type lvalue */ /* pointer variable to a float type lvalue */ int i, a[5], *q; /* combined declaration */ CS4 - Introduction to Scientific Computing and Problem Solving
7 Pointer Variables as Lvalues So how do we store an address in a pointer? One can simply refer to a particular address by a numerical constant; this is usually not so interesting neither likely to be correct since we often don't (or want to) know the exact address numbers! int *p; p = ; /* address of some memory location */ CS4 - Introduction to Scientific Computing and Problem Solving Address Operator & Pointers are most frequently used in conjunction with & (address) operator, which obtains the address of a variable The reference type can be any type (basic or user-defined, see next lecture) int *p, i=1; p = &i; /* store address of variable i */ All we care about is that p points to the address of another variable - say i - while the actual numerical address is irrelevant int *p, a[5]; p = &a[0]; /* store address of element a[0] */ CS4 - Introduction to Scientific Computing and Problem Solving
8 8 Pointer Assignment Pointers can also be copied by using them in assignment statements int *p, *q, i=-2341; p = &i; /* p stores address of variable i */ q = p; /* q stores value of p which is simply the address of i */ ? p p p ? q? q q i i i CS4 - Introduction to Scientific Computing and Problem Solving To Point or Not to Point - "What's the Point?" Modifying pointer variables in assignment operations will not affect the actual value stored in a variable int i=0, j=1; int *p = &i, *q; q = p; /* q stores value of p = address of i */ q = &j; /* q now stores address of j */ p = q; /* p points to j as well */ /* the values of variables i and j have not been changed by this "exchange of addresses" */ printf("i=%d, j=%d\n", i, j); CS4 - Introduction to Scientific Computing and Problem Solving
9 9 Indirection Operator * Once we have the address of a memory location (Lvalue) stored in a pointer, how do we get to the value stored there? Access is provided through the indirection operator * Also called dereferencing Different role of * int i=1001, j, k; int *p; What is the value of j and k? p = &i; /* address operator, stores address of i in p */ j = *p; /* indirection operator, assigns value stored in the address pointed to by p in j */ i = 0; /* changes the value of i */ k = *p; /* indirection operator */ CS4 - Introduction to Scientific Computing and Problem Solving Pointer Confusion? & & * * & * Although the concept of a pointer variable is very simple, the use of pointer variables can sometimes be confusing Consequently many programming errors in C are the result of incorrect usage of pointer variables CS4 - Introduction to Scientific Computing and Problem Solving
10 10 Pointer Confusion? Why are pointers potentially confusing? We always have to be aware of the difference between an address and the value stored at an address & & * * & * int i=1000, j=2000; int *p, *q; p = &i; q = &j; *p = *q; /* copies an integer value */ p = q; /* copies an address */ CS4 - Introduction to Scientific Computing and Problem Solving Pointer Confusion? & & * * & * Why are pointers potentially confusing? Via the indirection operator pointer variables can be used as aliases, i.e., there are multiple "names" referring to the same Lvalue int i = 1, *p, *q; p = &i; q = &i; *p = 2; /* i is now 2 as well */ *q = 3; /* i (and *p) is now 3 as well */ CS4 - Introduction to Scientific Computing and Problem Solving
11 11 Pointer Example (1) Let's look at a simple example again: i int i = 1, *p, *q; ? p ? q p = &i; q = p ; i p q CS4 - Introduction to Scientific Computing and Problem Solving Pointer Example (2) i *p = 2; p q i *q = 3; p q CS4 - Introduction to Scientific Computing and Problem Solving
12 12 Another Example #include <stdio.h> int main () { double *p1, *p2, b = 5.6; /* p1 gets the address of b */ p1 = &b; printf("b is now %lf\n", b); /* change b by dereferencing the pointer */ *p1 = 7.5; printf("b is now %lf\n", b); /* make another pointer to b */ p2 = p1; /* change b again, by dereferencing the new pointer */ *p2 = 9.3; printf("b is now %lf\n", b); } return 0; CS4 - Introduction to Scientific Computing and Problem Solving More Pointer Pitfalls Dereferencing a pointer variable using the indirection operator (*) when it has not been initialized properly can lead to (extremely!) undesirable program behavior int *p; /* an uninitialized pointer variable */ *p = 0; /* manipulating a random memory location */ int i; /* an integer variable */ scanf ("%d", i); /* should have used &i */ Segmentation fault CS4 - Introduction to Scientific Computing and Problem Solving
13 13 NULL Thou shalt not follow the NULL pointer, for chaos and madness await thee at its end Commandments for C Programmers by H. Spencer As a defensive measure, it is useful to assign a special (constant) value to uninitialized pointer variables This special value is called NULL, and it is different from every valid address #include <stdio.h> int *p = NULL; if (p == NULL) printf("invalid pointer!\n"); else printf("dereferencing = %d\n",*p); CS4 - Introduction to Scientific Computing and Problem Solving Pointers as Function Arguments Pointers can be passed as parameters in functions just like any other data type Passing a pointer to a variable is known as passing by reference If we pass a variable by value, the value gets copied and we cannot modify the variable in a function Pointers offer a solution to this problem: instead of passing a variable, we pass a pointer to the variable A pointer argument provides the address through which the function can alter the value of the original variable CS4 - Introduction to Scientific Computing and Problem Solving
14 14 Pointers as Function Arguments Here is a simple example of a function that sets a variable to zero /* * Function that sets the value of an int * Lvalue to zero using a pointer variable as * an argument */ void settozero(int *ptr) { *ptr = 0; } int main() { int i=1001; printf("before = %d\n",i); settozero(&i); printf("after = %d\n",i); } return 0; CS4 - Introduction to Scientific Computing and Problem Solving Example: Step by Step int i = 1001; i 1001 settozero(&i); settozero(int *ptr) i ptr *ptr = 0; i ptr CS4 - Introduction to Scientific Computing and Problem Solving
15 15 Pointers as Local Variables Use a pointer as a parameter to allow the function to modify variables What happens if a function modifies a parameter which happens to be a pointer variable? Nothing, it's a local variable void SetToZero(int *ptr) { *ptr = 0; /* has an effect outside of the function */ ptr = NULL; /* has no(!!) effect outside of the function */ } CS4 - Introduction to Scientific Computing and Problem Solving Passing by Reference Passing by reference provides a way for functions to return multiple values /* Compute maximum and minimum value in an array */ void maxmin(double a[], int n, double *max, double *min) { *max = *min = a[n-1]; for (n = n-2; n >= 0; n--) } [...] if (a[n] > *max) *max = a[n]; else if (a[n] < *min) *min = a[n]; Better: (by operating on copies of addresses) to manipulate the original contents of multiple input parameters double a[size], largest, smallest; [...] maxmin(a, SIZE, &largest, &smallest); printf("max = %lf, min = %lf\n", largest, smallest); CS4 - Introduction to Scientific Computing and Problem Solving
16 16 Pointers in C! Three is a very special number. It pervades religion, psychology, art, literature and more! This demo will show you some basic uses of pointers in C while exploring this magical and mystical number! CS4 - Introduction to Scientific Computing and Problem Solving scanf - Revisited We have been using "passing by reference" since the beginning in arguments to the scanf function We want scanf to actually return the input values in the variables passed as arguments #include <stdio.h> int main() { int i,j ; scanf ("%d%d", &i, &j); /* pass by reference */ printf("read in %d and %d\n", i, j); /* pass by value */ } return 0; CS4 - Introduction to Scientific Computing and Problem Solving
17 17 Swap Here is an example to implement a swap function using pointers: /* * Function to swap values of two integer variables */ void swap(int *a, int *b) { int itmp; itmp = *a; *a = *b; *b = itmp; } [...] int x=1, y=2; swap(&x, &y); swap( x, y); //this would not work CS4 - Introduction to Scientific Computing and Problem Solving Addresses of Array Elements The address of an array element can be determined by the address operator & int arr[10]; int *ptr ; ptr = &arr[0]; /* the address of the 1st array element */ ptr = &arr[2]; /* the address of the 3rd array element */ CS4 - Introduction to Scientific Computing and Problem Solving
18 18 Pointer Arithmetic (1) We can perform arithmetic operations with pointer variables Pointer arithmetic is defined taking into account the pointer variable's base type (now you know why that was important!) int arr[10]; int *ptr1, *ptr2 ; ptr1 = &arr[2]; /* the address of the 3rd array element */ ptr2 = &arr[0] + 2 ; /* equivalent */ Notice how this is different from simply adding 2 to the actual address; pointer arithmetic takes into account that an integer element occupies sizeof(int) bytes CS4 - Introduction to Scientific Computing and Problem Solving Pointer Arithmetic (2) Pointers can be used as a "cursor" to move along an array; moving n elements forward or backward can simply be achieved by: int arr[10], *ptr = &arr[0]; ptr += 5; /* move 5 elements forward, points to arr[5] now */ ptr -= 2; /* move 2 elements backward, points to arr[3] now */ ptr += 1; /* move 1 element forward, points to arr[4] now */ ptr += 6; /* oops! */ Pointers can also be subtracted int diff, arr[10], *p = &arr[2], *q = &arr[7]; diff = q - p; printf( Pointer difference = %d\n", diff) ; CS4 - Introduction to Scientific Computing and Problem Solving
19 Pointer Arithmetic (3) Step by step example: int arr[10]={0,1,1,2,3,5,8,13,21,34}; int *ptr = &arr[0]; ptr += 5; *ptr = -1; ptr -= 2; *ptr = -2; ptr += 1; *ptr = -3; ptr += 6; ptr p ptr+=6; ptr = &arr[0]; ptr-=2; ptr+=1; ptr+=5; *ptr=-2; *ptr=-3; *ptr=-1; arr CS4 - Introduction to Scientific Computing and Problem Solving Array Names as Pointers C treats an array name as a pointer to the first element int i, arr[n]; for (i = 0; i < N; i++) *(arr + i) = i; /* equivalent to arr[i] = i; */ int *p; /* move pointer over array */ for (p = arr; p < arr + N; p++) sum += *p; However, array names are constant pointer variables, i.e., one cannot assign it a new value (address) int i, arr[n]; for (i = 0; i < N; i++) *arr++ = i; /* NO!!! */ CS4 - Introduction to Scientific Computing and Problem Solving
20 Pointers as Array Names In many situations, it is also possible to treat a pointer as an array name In particular one can use the subscript operator (i.e., brackets []) to access array elements int i, arr[n], *p ; [...] /* fill array here */ p = arr; for (i = 0; i < N; i++) p[i] = 0; as if p is an array name although it is the name of a pointer variable CS4 - Introduction to Scientific Computing and Problem Solving Arrays as Function Arguments Looking back we see now why arrays are passed as function arguments by reference: because the array name is nothing but a (constant) pointer variable /* Multiplies each element of an array by a constant */ void mult(double a[], int num, double value) { int i; for (i = 0; i < num; i++) a[i] *= value; } [...] double b[5] = {1e-1, 1e-2, 1e-3, 1e-4, 1e-5 }; mult(b, 5, 2.0); CS4 - Introduction to Scientific Computing and Problem Solving
21 21 Pointers & Multi-dimensional Arrays Pointers can also point to elements in a multidimensional array Remember the memory layout of 2D arrays: rows are stored consecutively in memory a row 0 row 1 row 2 a[0][0]a[0][1]a[0][2]a[1][0]a[1][1]a[1][2]a[2][0]a[2][1]a[2][2] memory (sequential) #define SIZE 3 int a[size][size]; /* treated as 1D array (a[]) with elements that are 1D arrays (the rows) */ int *row, n = 1 ; row = a[n]; /* pointer to the first element in n-th row */ CS4 - Introduction to Scientific Computing and Problem Solving Relational Operators on Pointers Pointers can also be compared by relational operators <, >, <=, >=, == int arr[100], *p = &arr[10], *q = &arr[21]; [...] /* some pointer arithmetic here */ if (p == q) printf("p and q point to the same element.\n"); else if (p < q) printf("element index of p smaller than that of q.\n"); else printf("element index of p greater than that of q.\n"); CS4 - Introduction to Scientific Computing and Problem Solving
22 22 Using Pointers in Array Processing (1) A first useful example of pointer arithmetic: Compute the sum of the elements in an array #define N 10 int arr[n], *p = NULL ; int sum = 0; [...] /* fill array elements here */ /* move pointer over array */ for (p = &arr[0]; p < &arr[n]; p++) sum += *p; printf("sum of array elements = %d\n", sum); CS4 - Introduction to Scientific Computing and Problem Solving Using Pointers in Array Processing (2) A closer look at the details pointer variable points to first array element pointer variable advances to next element in array for (p = &arr[0]; p < &arr[n]; p++) sum += *p; pointer dereferencing (indirection operator) relational operator, check whether past last array element CS4 - Introduction to Scientific Computing and Problem Solving
23 23 Using Pointers in Array Processing (3a) p arr p = &arr[0]; sum 11 sum += *p; p p++ arr sum 6 sum += *p; CS4 - Introduction to Scientific Computing and Problem Solving Using Pointers in Array Processing (3b) p arr p sum 9 sum += *p; p p++ arr sum 2 sum += *p; CS4 - Introduction to Scientific Computing and Problem Solving
24 Subscripting vs. Pointers In our example, the use of pointers could easily be replaced by subscripting using a counter int *p; /* move pointer over array */ for (p = &arr[0]; p < &arr[n]; p++) sum += *p; int i; /* use subscripting */ for (i = 0; i < N; i++) sum += arr[i]; Some compilers will produce more efficient code when using pointer arithmetic CS4 - Introduction to Scientific Computing and Problem Solving Combining Operators Pointer operators can be combined Example: initialize array elements to zero #define N 100 [...] int *p = &arr[0], *last = &arr[n-1]; while (p <= last) *p++ = 0; /* dereference, assign and increment */ CS4 - Introduction to Scientific Computing and Problem Solving
First of all, it is a variable, just like other variables you studied
Pointers: Basics 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 address (rather than the value)
More informationArrays. CS10001: Programming & Data Structures. Pallab Dasgupta Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur
Arrays CS10001: Programming & Data Structures Pallab Dasgupta Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur Array Many applications require multiple data items that have common
More informationAgenda. Peer Instruction Question 1. Peer Instruction Answer 1. Peer Instruction Question 2 6/22/2011
CS 61C: Great Ideas in Computer Architecture (Machine Structures) Introduction to C (Part II) Instructors: Randy H. Katz David A. Patterson http://inst.eecs.berkeley.edu/~cs61c/sp11 Spring 2011 -- Lecture
More informationGoals of this Lecture
C Pointers Goals of this Lecture Help you learn about: Pointers and application Pointer variables Operators & relation to arrays 2 Pointer Variables The first step in understanding pointers is visualizing
More informationComputer Programming. C Array is a collection of data belongings to the same data type. data_type array_name[array_size];
Arrays An array is a collection of two or more adjacent memory cells, called array elements. Array is derived data type that is used to represent collection of data items. C Array is a collection of data
More informationPointers (part 1) What are pointers? EECS We have seen pointers before. scanf( %f, &inches );! 25 September 2017
Pointers (part 1) EECS 2031 25 September 2017 1 What are pointers? We have seen pointers before. scanf( %f, &inches );! 2 1 Example char c; c = getchar(); printf( %c, c); char c; char *p; c = getchar();
More informationTo declare an array in C, a programmer specifies the type of the elements and the number of elements required by an array as follows
Unti 4: C Arrays Arrays a kind of data structure that can store a fixed-size sequential collection of elements of the same type An array is used to store a collection of data, but it is often more useful
More informationLab 3. Pointers Programming Lab (Using C) XU Silei
Lab 3. Pointers Programming Lab (Using C) XU Silei slxu@cse.cuhk.edu.hk Outline What is Pointer Memory Address & Pointers How to use Pointers Pointers Assignments Call-by-Value & Call-by-Address Functions
More informationPointers. Memory. void foo() { }//return
Pointers Pointers Every location in memory has a unique number assigned to it called it s address A pointer is a variable that holds a memory address A pointer can be used to store an object or variable
More informationArrays and Strings. Arash Rafiey. September 12, 2017
September 12, 2017 Arrays Array is a collection of variables with the same data type. Arrays Array is a collection of variables with the same data type. Instead of declaring individual variables, such
More informationArrays and Pointers. CSE 2031 Fall November 11, 2013
Arrays and Pointers CSE 2031 Fall 2013 November 11, 2013 1 Arrays l Grouping of data of the same type. l Loops commonly used for manipulation. l Programmers set array sizes explicitly. 2 Arrays: Example
More informationHomework #3 CS2255 Fall 2012
Homework #3 CS2255 Fall 2012 MULTIPLE CHOICE 1. The, also known as the address operator, returns the memory address of a variable. a. asterisk ( * ) b. ampersand ( & ) c. percent sign (%) d. exclamation
More informationESC101N Fundamentals of Computing
ESC101N Fundamentals of Computing Arnab Bhattacharya arnabb@iitk.ac.in Indian Institute of Technology, Kanpur http://www.iitk.ac.in/esc101/ 1 st semester, 2010-11 Tue, Wed, Fri 0800-0900 at L7 Arnab Bhattacharya
More informationCS 2461: Computer Architecture I
Next: Pointers, Arrays, Structs... : Computer Architecture I The real fun stuff in C.. Pointers and Arrays Read Chapters 16, 18 of text Functions, Arrays, Pointers Dynamic data structures Allocating space
More informationOutput of sample program: Size of a short is 2 Size of a int is 4 Size of a double is 8
Pointers Variables vs. Pointers: A variable in a program is something with a name and a value that can vary. The way the compiler and linker handles this is that it assigns a specific block of memory within
More informationOutline. Computer Memory Structure Addressing Concept Introduction to Pointer Pointer Manipulation Summary
Pointers 1 2 Outline Computer Memory Structure Addressing Concept Introduction to Pointer Pointer Manipulation Summary 3 Computer Memory Revisited Computers store data in memory slots Each slot has an
More informationParameter passing. Programming in C. Important. Parameter passing... C implements call-by-value parameter passing. UVic SEng 265
Parameter passing Programming in C UVic SEng 265 Daniel M. German Department of Computer Science University of Victoria 1 SEng 265 dmgerman@uvic.ca C implements call-by-value parameter passing int a =
More informationLecture 8: Pointer Arithmetic (review) Endianness Functions and pointers
CSE 30: Computer Organization and Systems Programming Lecture 8: Pointer Arithmetic (review) Endianness Functions and pointers Diba Mirza University of California, San Diego 1 Q: Which of the assignment
More informationPrinciples of C and Memory Management
COMP281 Lecture 8 Principles of C and Memory Management Dr Lei Shi Last Lecture Pointer Basics Previous Lectures Arrays, Arithmetic, Functions Last Lecture Pointer Basics Previous Lectures Arrays, Arithmetic,
More informationWhat have we learned about when we learned about function parameters? 1-1
What have we learned about when we learned about function parameters? 1-1 What have we learned about when we learned about function parameters? Call-by-Value also known as scalars (eg. int, double, char,
More informationMYcsvtu Notes LECTURE 34. POINTERS
LECTURE 34 POINTERS Pointer Variable Declarations and Initialization Pointer variables Contain memory addresses as their values Normal variables contain a specific value (direct reference) Pointers contain
More informationArrays and Pointers. Arrays. Arrays: Example. Arrays: Definition and Access. Arrays Stored in Memory. Initialization. EECS 2031 Fall 2014.
Arrays Arrays and Pointers l Grouping of data of the same type. l Loops commonly used for manipulation. l Programmers set array sizes explicitly. EECS 2031 Fall 2014 November 11, 2013 1 2 Arrays: Example
More informationComputer Programming Lecture 12 Pointers
Computer Programming Lecture 2 Pointers Assist.Prof.Dr. Nükhet ÖZBEK Ege University Department of Electrical & Electronics Engineering nukhet.ozbek@ege.edu.tr Topics Introduction to Pointers Pointers and
More information[0569] p 0318 garbage
A Pointer is a variable which contains the address of another variable. Declaration syntax: Pointer_type *pointer_name; This declaration will create a pointer of the pointer_name which will point to the
More informationPointers. Part VI. 1) Introduction. 2) Declaring Pointer Variables. 3) Using Pointers. 4) Pointer Arithmetic. 5) Pointers and Arrays
EE105: Software Engineering II Part 6 Pointers page 1 of 19 Part VI Pointers 1) Introduction 2) Declaring Pointer Variables 3) Using Pointers 4) Pointer Arithmetic 5) Pointers and Arrays 6) Pointers and
More informationEM108 Software Development for Engineers
EE108 Section 6 Pointers page 1 of 20 EM108 Software Development for Engineers Section 6 - Pointers 1) Introduction 2) Declaring Pointer Variables 3) Using Pointers 4) Pointer Arithmetic 5) Pointers and
More informationPointers. 1 Background. 1.1 Variables and Memory. 1.2 Motivating Pointers Massachusetts Institute of Technology
Introduction to C++ Massachusetts Institute of Technology ocw.mit.edu 6.096 Pointers 1 Background 1.1 Variables and Memory When you declare a variable, the computer associates the variable name with a
More informationJagannath Institute of Management Sciences Lajpat Nagar. BCA II Sem. C Programming
Jagannath Institute of Management Sciences Lajpat Nagar BCA II Sem C Programming UNIT I Pointers: Introduction to Pointers, Pointer Notation,Decalaration and Initialization, Accessing variable through
More informationSir Syed University of Engineering and Technology. Computer Programming & Problem Solving ( CPPS ) Pointers. Chapter No 7
Computer Programming & Problem Solving ( CPPS ) Chapter No 7 Sir Syed University of Engineering & Technology Computer Engineering Department University Road, Karachi-75300, PAKISTAN Muzammil Ahmad Khan
More informationLecture 2: C Programm
0 3 E CS 1 Lecture 2: C Programm ing C Programming Procedural thought process No built in object abstractions data separate from methods/functions Low memory overhead compared to Java No overhead of classes
More informationComputer Science & Engineering 150A Problem Solving Using Computers
Computer Science & Engineering 150A Problem Solving Using Computers Lecture 06 - Stephen Scott Adapted from Christopher M. Bourke 1 / 30 Fall 2009 Chapter 8 8.1 Declaring and 8.2 Array Subscripts 8.3 Using
More informationPointers and Arrays 1
Pointers and Arrays 1 Pointers and Arrays 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
More informationC++ for Engineers and Scientists. Third Edition. Chapter 12 Pointers
C++ for Engineers and Scientists Third Edition Chapter 12 Pointers CSc 10200! Introduction to Computing Lecture 24 Edgardo Molina Fall 2013 City College of New York 2 Objectives In this chapter you will
More informationLanguage comparison. C has pointers. Java has references. C++ has pointers and references
Pointers CSE 2451 Language comparison C has pointers Java has references C++ has pointers and references Pointers Values of variables are stored in memory, at a particular location A location is identified
More informationPointers. September 13, 2017 Hassan Khosravi / Geoffrey Tien 1
Pointers September 13, 2017 Hassan Khosravi / Geoffrey Tien 1 Multi-dimensional arrays A two-dimensional array is specified using two indices First index denotes the row, second index denotes column int
More informationCS 61c: Great Ideas in Computer Architecture
Arrays, Strings, and Some More Pointers June 24, 2014 Review of Last Lecture C Basics Variables, functioss, control flow, types, structs Only 0 and NULL evaluate to false Pointers hold addresses Address
More informationArrays and Pointers in C. Alan L. Cox
Arrays and Pointers in C Alan L. Cox alc@rice.edu 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
More informationArrays and Pointers (part 1)
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];
More informationProgramming for Electrical and Computer Engineers. Pointers and Arrays
Programming for Electrical and Computer Engineers Pointers and Arrays Dr. D. J. Jackson Lecture 12-1 Introduction C allows us to perform arithmetic addition and subtraction on pointers to array elements.
More informationPROGRAMMAZIONE I A.A. 2017/2018
PROGRAMMAZIONE I A.A. 2017/2018 A pointer is a variable whose value is the address of another variable, i.e., direct address of the memory location. DECLARING POINTERS POINTERS A pointer represents both
More informationC Pointers. Abdelghani Bellaachia, CSCI 1121 Page: 1
C Pointers 1. Objective... 2 2. Introduction... 2 3. Pointer Variable Declarations and Initialization... 3 4. Reference operator (&) and Dereference operator (*) 6 5. Relation between Arrays and Pointers...
More informationC++ for Java Programmers
Basics all Finished! Everything we have covered so far: Lecture 5 Operators Variables Arrays Null Terminated Strings Structs Functions 1 2 45 mins of pure fun Introduction Today: Pointers Pointers Even
More informationExercise 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!
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! Exercise 3 / Ch.8 Given the following array, write code
More informationPointer Basics. Lecture 13 COP 3014 Spring March 28, 2018
Pointer Basics Lecture 13 COP 3014 Spring 2018 March 28, 2018 What is a Pointer? A pointer is a variable that stores a memory address. Pointers are used to store the addresses of other variables or memory
More informationWhat is an algorithm?
Announcements CS 142 C++ Pointers Reminder Program 6 due Sunday, Nov. 9 th by 11:55pm 11/3/2014 2 Pointers and the Address Operator Pointer Variables Each variable in a program is stored at a unique address
More informationCS 61C: Great Ideas in Computer Architecture. C Arrays, Strings, More Pointers
CS 61C: Great Ideas in Computer Architecture C Arrays, Strings, More Pointers Instructor: Justin Hsia 6/20/2012 Summer 2012 Lecture #3 1 Review of Last Lecture C Basics Variables, Functions, Flow Control,
More informationProcedural programming with C
Procedural programming with C Dr. C. Constantinides Department of Computer Science and Software Engineering Concordia University Montreal, Canada August 11, 2016 1 / 77 Functions Similarly to its mathematical
More informationArrays in C. Prof. Indranil Sen Gupta Dept. of Computer Science & Engg. Indian Institute of Technology Kharagpur. Basic Concept
Arrays in C Prof. Indranil Sen Gupta Dept. of Computer Science & Engg. Indian Institute of Technology Kharagpur 1 Basic Concept Many applications require multiple data items that have common characteristics.
More informationPointers and Structure. Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island
Pointers and Structure Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island 1 Pointer Variables Each variable in a C program occupies space in
More informationMemory, Arrays & Pointers
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
More informationPointers. Introduction
Pointers Spring Semester 2007 Programming and Data Structure 1 Introduction A pointer is a variable that represents the location (rather than the value) of a data item. They have a number of useful applications.
More informationModule 6: Array in C
1 Table of Content 1. Introduction 2. Basics of array 3. Types of Array 4. Declaring Arrays 5. Initializing an array 6. Processing an array 7. Summary Learning objectives 1. To understand the concept of
More informationArrays and Pointers (part 1)
Arrays and Pointers (part 1) CSE 2031 Fall 2010 17 October 2010 1 Arrays Grouping of data of the same type. Loops commonly used for manipulation. Programmers set array sizes explicitly. 2 1 Arrays: Example
More informationAt the end of this module, the student should be able to:
INTRODUCTION One feature of the C language which can t be found in some other languages is the ability to manipulate pointers. Simply stated, pointers are variables that store memory addresses. This is
More informationFORM 1 (Please put your name and section number (001/10am or 002/2pm) on the scantron!!!!) CS 161 Exam II: True (A)/False(B) (2 pts each):
FORM 1 (Please put your name and section number (001/10am or 002/2pm) on the scantron!!!!) CS 161 Exam II: True (A)/False(B) (2 pts each): 1. If a function has default arguments, they can be located anywhere
More informationKOM3191 Object Oriented Programming Dr Muharrem Mercimek ARRAYS ~ VECTORS. KOM3191 Object-Oriented Computer Programming
KOM3191 Object Oriented Programming Dr Muharrem Mercimek 1 ARRAYS ~ VECTORS KOM3191 Object-Oriented Computer Programming KOM3191 Object Oriented Programming Dr Muharrem Mercimek 2 What is an array? Arrays
More informationAdministrivia. Introduction to Computer Systems. Pointers, cont. Pointer example, again POINTERS. Project 2 posted, due October 6
CMSC 313 Introduction to Computer Systems Lecture 8 Pointers, cont. Alan Sussman als@cs.umd.edu Administrivia Project 2 posted, due October 6 public tests s posted Quiz on Wed. in discussion up to pointers
More informationBinary Representation. Decimal Representation. Hexadecimal Representation. Binary to Hexadecimal
Decimal Representation Binary Representation Can interpret decimal number 4705 as: 4 10 3 + 7 10 2 + 0 10 1 + 5 10 0 The base or radix is 10 Digits 0 9 Place values: 1000 100 10 1 10 3 10 2 10 1 10 0 Write
More informationDecimal Representation
Decimal Representation Can interpret decimal number 4705 as: 4 10 3 + 7 10 2 + 0 10 1 + 5 10 0 The base or radix is 10 Digits 0 9 Place values: 1000 100 10 1 10 3 10 2 10 1 10 0 Write number as 4705 10
More informationCS162 - POINTERS. Lecture: Pointers and Dynamic Memory
CS162 - POINTERS Lecture: Pointers and Dynamic Memory What are pointers Why dynamically allocate memory How to dynamically allocate memory What about deallocation? Walk thru pointer exercises 1 CS162 -
More informationCS61C Machine Structures. Lecture 4 C Pointers and Arrays. 1/25/2006 John Wawrzynek. www-inst.eecs.berkeley.edu/~cs61c/
CS61C Machine Structures Lecture 4 C Pointers and Arrays 1/25/2006 John Wawrzynek (www.cs.berkeley.edu/~johnw) www-inst.eecs.berkeley.edu/~cs61c/ CS 61C L04 C Pointers (1) Common C Error There is a difference
More informationPOINTER & REFERENCE VARIABLES
Lecture 9 POINTER & REFERENCE VARIABLES Declaring data pointer variables Assignment operations with pointers Referring objects using pointer variables Generic pointers Operations with pointer variables
More informationContent. In this chapter, you will learn:
ARRAYS & HEAP Content In this chapter, you will learn: To introduce the array data structure To understand the use of arrays To understand how to define an array, initialize an array and refer to individual
More informationC++ ARRAYS POINTERS POINTER ARITHMETIC. Problem Solving with Computers-I
C++ ARRAYS POINTERS POINTER ARITHMETIC Problem Solving with Computers-I General model of memory Sequence of adjacent cells Each cell has 1-byte stored in it Each cell has an address (memory location) Memory
More informationPhysics 2660: Fundamentals of Scientific Computing. Lecture 3 Instructor: Prof. Chris Neu
Physics 2660: Fundamentals of Scientific Computing Lecture 3 Instructor: Prof. Chris Neu (chris.neu@virginia.edu) Announcements Weekly readings will be assigned and available through the class wiki home
More informationDECLARAING AND INITIALIZING POINTERS
DECLARAING AND INITIALIZING POINTERS Passing arguments Call by Address Introduction to Pointers Within the computer s memory, every stored data item occupies one or more contiguous memory cells (i.e.,
More informationWhy Pointers. Pointers. Pointer Declaration. Two Pointer Operators. What Are Pointers? Memory address POINTERVariable Contents ...
Why Pointers Pointers They provide the means by which functions can modify arguments in the calling function. They support dynamic memory allocation. They provide support for dynamic data structures, such
More informationPointers. A pointer value is the address of the first byte of the pointed object in the memory. A pointer does not know how many bytes it points to.
Pointers A pointer is a memory address of an object of a specified type, or it is a variable which keeps such an address. Pointer properties: P (pointer) 12316 12316 (address) Typed object A pointer value
More informationPointers. Pointer Variables. Chapter 11. Pointer Variables. Pointer Variables. Pointer Variables. Declaring Pointer Variables
Chapter 11 Pointers The first step in understanding pointers is visualizing what they represent at the machine level. In most modern computers, main memory is divided into bytes, with each byte capable
More informationECE 15B COMPUTER ORGANIZATION
ECE 15B COMPUTER ORGANIZATION Lecture 13 Strings, Lists & Stacks Announcements HW #3 Due next Friday, May 15 at 5:00 PM in HFH Project #2 Due May 29 at 5:00 PM Project #3 Assigned next Thursday, May 19
More informationPointers. 10/5/07 Pointers 1
Pointers 10/5/07 Pointers 1 10/5/07 Pointers 2 Variables Essentially, the computer's memory is made up of bytes. Each byte has an address, associated with it. 10/5/07 Pointers 3 Variable For example 1:#include
More informationLecture 4: Outline. Arrays. I. Pointers II. III. Pointer arithmetic IV. Strings
Lecture 4: Outline I. Pointers A. Accessing data objects using pointers B. Type casting with pointers C. Difference with Java references D. Pointer pitfalls E. Use case II. Arrays A. Representation in
More informationFundamental of Programming (C)
Borrowed from lecturer notes by Omid Jafarinezhad Fundamental of Programming (C) Lecturer: Vahid Khodabakhshi Lecture 9 Pointer Department of Computer Engineering 1/46 Outline Defining and using Pointers
More informationAnnouncements. assign0 due tonight. Labs start this week. No late submissions. Very helpful for assign1
Announcements assign due tonight No late submissions Labs start this week Very helpful for assign1 Goals for Today Pointer operators Allocating memory in the heap malloc and free Arrays and pointer arithmetic
More informationPointers and Arrays A QUICK PREVIEW OF FOR CHAPTERS 10 AND 11 CMPE13. Cyrus Bazeghi
Pointers and Arrays A QUICK PREVIEW OF FOR CHAPTERS 10 AND 11 Cyrus Bazeghi POINTERS AND ARRAYS We have briefly seen these before, here are the details Pointer Array Address of a variable in memory Allows
More informationLecture06: Pointers 4/1/2013
Lecture06: Pointers 4/1/2013 Slides modified from Yin Lou, Cornell CS2022: Introduction to C 1 Pointers A ointer is a variable that contains the (memory) address of another variable What is a memory address?
More informationCS2351 Data Structures. Lecture 7: A Brief Review of Pointers in C
CS2351 Data Structures Lecture 7: A Brief Review of Pointers in C 1 About this lecture Pointer is a useful object that allows us to access different places in our memory We will review the basic use of
More informationLecture 5: Outline. I. Multi- dimensional arrays II. Multi- level arrays III. Structures IV. Data alignment V. Linked Lists
Lecture 5: Outline I. Multi- dimensional arrays II. Multi- level arrays III. Structures IV. Data alignment V. Linked Lists Multidimensional arrays: 2D Declaration int a[3][4]; /*Conceptually 2D matrix
More informationC How to Program, 7/e by Pearson Education, Inc. All Rights Reserved.
C How to Program, 7/e This chapter serves as an introduction to data structures. Arrays are data structures consisting of related data items of the same type. In Chapter 10, we discuss C s notion of
More informationCS113: Lecture 5. Topics: Pointers. Pointers and Activation Records
CS113: Lecture 5 Topics: Pointers Pointers and Activation Records 1 From Last Time: A Useless Function #include void get_age( int age ); int age; get_age( age ); printf( "Your age is: %d\n",
More informationArrays Arrays and pointers Loops and performance Array comparison Strings. John Edgar 2
CMPT 125 Arrays Arrays and pointers Loops and performance Array comparison Strings John Edgar 2 Python a sequence of data access elements with [index] index from [0] to [len-1] dynamic length heterogeneous
More informationPDS Class Test 2. Room Sections No of students
PDS Class Test 2 Date: October 27, 2016 Time: 7pm to 8pm Marks: 20 (Weightage 50%) Room Sections No of students V1 Section 8 (All) Section 9 (AE,AG,BT,CE, CH,CS,CY,EC,EE,EX) V2 Section 9 (Rest, if not
More informationLectures 5-6: Introduction to C
Lectures 5-6: Introduction to C Motivation: C is both a high and a low-level language Very useful for systems programming Faster than Java This intro assumes knowledge of Java Focus is on differences Most
More informationCS61C : Machine Structures
inst.eecs.berkeley.edu/~cs61c CS61C : Machine Structures Lecture 3 Introduction to C (pt 2) 2010-06-23! C help session: Tonight 7:00-9:00pm @ 306 Soda!!!Instructor Paul Pearce! The typical! development
More informationReview! * follows a pointer to its value! & gets the address of a variable! Pearce, Summer 2010 UCB! ! int x = 1000; Pearce, Summer 2010 UCB!
CS61C L03 Introduction to C (pt 2) (1)! inst.eecs.berkeley.edu/~cs61c CS61C : Machine Structures Lecture 3 Introduction to C (pt 2) 2010-06-23!!!Instructor Paul Pearce! The typical! development cycle!
More informationMore Pointers Week 11
More Pointers Week 11 Pointer Variable Normal variables Contain a specific value (direct reference) Pointer variables Contain memory addresses as their values countptr count 7 count 7 Pointer Expressions
More informationA pointer is a variable just like other variable. The only difference from other variables is that it stores the memory address other variables.
Lecture 9 Pointers A pointer is a variable just like other variable. The only difference from other variables is that it stores the memory address other variables. This variable may be of type int, char,
More informationHW1 due Monday by 9:30am Assignment online, submission details to come
inst.eecs.berkeley.edu/~cs61c CS61CL : Machine Structures Lecture #2 - C Pointers and Arrays Administrivia Buggy Start Lab schedule, lab machines, HW0 due tomorrow in lab 2009-06-24 HW1 due Monday by 9:30am
More informationChapter 12: Pointers and Arrays. Chapter 12. Pointers and Arrays. Copyright 2008 W. W. Norton & Company. All rights reserved.
Chapter 12 Pointers and Arrays 1 Introduction C allows us to perform arithmetic addition and subtraction on pointers to array elements. This leads to an alternative way of processing arrays in which pointers
More informationDynamic memory allocation (malloc)
1 Plan for today Quick review of previous lecture Array of pointers Command line arguments Dynamic memory allocation (malloc) Structures (Ch 6) Input and Output (Ch 7) 1 Pointers K&R Ch 5 Basics: Declaration
More informationWeek 7: Pointers and Arrays. BJ Furman 02OCT2009
Week 7: Pointers and Arrays BJ Furman 02OCT2009 The Plan for Today Closer look at pointers What is a pointer? Why use pointers? How can we use pointers? Pointer Examples Pointer Practice Learning Objectives
More informationReview of Important Topics in CS1600. Functions Arrays C-strings
Review of Important Topics in CS1600 Functions Arrays C-strings Array Basics Arrays An array is used to process a collection of data of the same type Examples: A list of names A list of temperatures Why
More informationSubject: Fundamental of Computer Programming 2068
Subject: Fundamental of Computer Programming 2068 1 Write an algorithm and flowchart to determine whether a given integer is odd or even and explain it. Algorithm Step 1: Start Step 2: Read a Step 3: Find
More informationC: Pointers. C: Pointers. Department of Computer Science College of Engineering Boise State University. September 11, /21
Department of Computer Science College of Engineering Boise State University September 11, 2017 1/21 Pointers A pointer is a variable that stores the address of another variable. Pointers are similar to
More informationFunctions. Arash Rafiey. September 26, 2017
September 26, 2017 are the basic building blocks of a C program. are the basic building blocks of a C program. A function can be defined as a set of instructions to perform a specific task. are the basic
More informationCOMP26120: Pointers in C (2018/19) Lucas Cordeiro
COMP26120: Pointers in C (2018/19) Lucas Cordeiro lucas.cordeiro@manchester.ac.uk Organisation Lucas Cordeiro (Senior Lecturer, FM Group) lucas.cordeiro@manchester.ac.uk Office: 2.44 Office hours: 10-11
More informationPointers as Arguments
Introduction as Arguments How it Works called program on start of execution xw = &i xf = &d after excution xw = &i xf = &d caller program i? d? i 3 d.14159 x 3.14159 x 3.14159 R. K. Ghosh (IIT-Kanpur)
More informationCOMPUTER APPLICATION
Total No. of Printed Pages 16 HS/XII/A.Sc.Com/CAP/14 2 0 1 4 COMPUTER APPLICATION ( Science / Arts / Commerce ) ( Theory ) Full Marks : 70 Time : 3 hours The figures in the margin indicate full marks for
More informationEastern Mediterranean University School of Computing and Technology Information Technology Lecture4 Pointers
Eastern Mediterranean University School of Computing and Technology Information Technology Lecture4 Pointers Pointers, Addresses and Dereferencing What is a pointer? What is a memory address? What does
More informationC for Java Programmers 1. Last Week. Overview of the differences between C and Java. The C language (keywords, types, functies, etc.
C for Java Programmers 1 Last Week Very short history of C Overview of the differences between C and Java The C language (keywords, types, functies, etc.) Compiling (preprocessor, compiler, linker) C for
More information