PROGRAMMAZIONE I A.A. 2017/2018

Similar documents
C Pointers. Indirection Indirection = referencing a value through a pointer. Creating Pointers. Pointer Declarations. Pointer Declarations

PROGRAMMAZIONE I A.A. 2017/2018

Variation of 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!

Procedural programming with C

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

Output of sample program: Size of a short is 2 Size of a int is 4 Size of a double is 8

POINTER & REFERENCE VARIABLES

DECLARAING AND INITIALIZING POINTERS

by Pearson Education, Inc. All Rights Reserved.

Lecture 14. No in-class files today. Homework 7 (due on Wednesday) and Project 3 (due in 10 days) posted. Questions?

Pointers. 10/5/07 Pointers 1

Fundamental of Programming (C)

Fundamentals of Programming Session 20

Why Pointers. Pointers. Pointer Declaration. Two Pointer Operators. What Are Pointers? Memory address POINTERVariable Contents ...

[0569] p 0318 garbage

Lab 3. Pointers Programming Lab (Using C) XU Silei

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

Tutorial 10 Pointers in C. Shuyue Hu

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

C Pointers. CS 2060 Week 6. Prof. Jonathan Ventura

Fundamentals of Programming Session 19

P.G.TRB - COMPUTER SCIENCE. c) data processing language d) none of the above

Problem Solving and 'C' Programming

Pointer Data Type and Pointer Variables

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

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

2.2 Pointers. Department of CSE

Binary Representation. Decimal Representation. Hexadecimal Representation. Binary to Hexadecimal

Decimal Representation

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

Goals of this Lecture

Introduction to Scientific Computing and Problem Solving

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

Fundamentals of Programming Session 20

C Pointers. 7.2 Pointer Variable Definitions and Initialization

Pointers as Arguments

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

C++ for Java Programmers

CS2351 Data Structures. Lecture 7: A Brief Review of Pointers in C

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

CSCI 171 Chapter Outlines

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

C++ Programming Chapter 7 Pointers

Example: Pointer Basics

... Lecture 12. Pointers

Programming for Engineers Pointers

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

SYSC 2006 C Winter 2012

Chapter 6 - Pointers

Arrays. Example: Run the below program, it will crash in Windows (TurboC Compiler)

Will introduce various operators supported by C language Identify supported operations Present some of terms characterizing operators

More about BOOLEAN issues

Computer Systems Principles. C Pointers

Computers Programming Course 6. Iulian Năstac

A complex expression to evaluate we need to reduce it to a series of simple expressions. E.g * 7 =>2+ 35 => 37. E.g.

Operators and Expressions:

Basic C Programming (2) Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island

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

1.3b Type Conversion

Lecture 05 POINTERS 1

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

Systems Programming and Computer Architecture ( )

Programming. Pointers, Multi-dimensional Arrays and Memory Management

! A pointer variable (or pointer): ! An asterisk is used to define a pointer variable. ! ptr is a pointer to an int or

Arrays, Pointers and Memory Management

Programming for Engineers Iteration

Fundamentals of Programming

Pointers. Pointer Variables. Chapter 11. Pointer Variables. Pointer Variables. Pointer Variables. Declaring Pointer Variables

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

PROGRAMMAZIONE I A.A. 2017/2018

Lecture 2: C Programm

A Fast Review of C Essentials Part I

PROGRAMMAZIONE I A.A. 2017/2018

Chapter 7 C Pointers

Chapter 7. Pointers. Copyright 2007 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

Operating Systems 2INC0 C course Pointer Advanced. Dr. Ir. Ion Barosan

Computer Programming Unit 3

C Pointers Pearson Education, Inc. All rights reserved.

Programming in C - Part 2

Expressions. Arithmetic expressions. Logical expressions. Assignment expression. n Variables and constants linked with operators

Memory, Arrays & Pointers

Fundamental of Programming (C)

MYcsvtu Notes LECTURE 34. POINTERS

Dynamic Allocation in C

CS 61c: Great Ideas in Computer Architecture

Arrays and Pointers in C. Alan L. Cox

A First Program - Greeting.cpp

Work relative to other classes

Intermediate Programming, Spring 2017*

Arrays and Pointers. CSE 2031 Fall November 11, 2013

PROGRAMMAZIONE I A.A. 2017/2018

EL2310 Scientific Programming

9/5/2018. Overview. The C Programming Language. Transitioning to C from Python. Why C? Hello, world! Programming in C

Sir Syed University of Engineering and Technology. Computer Programming & Problem Solving ( CPPS ) Pointers. Chapter No 7

Arrays and Pointers (part 1)

ESC101N Fundamentals of Computing

Homework #3 CS2255 Fall 2012

The C Programming Language. (with material from Dr. Bin Ren, William & Mary Computer Science)

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

Transcription:

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 the address and the type of an object. If an object or function has the type T, then a pointer to it has the derived type pointer to T. For example, if var is a float variable, then the expression &var whose value is the address of the float variable has the type pointer to float, or in C notation, the type float *. Because var doesn t move around in memory, the expression &var is a constant pointer. The declaration of a pointer to an object that is not an array has the following syntax: type * [type-qualifier-list] name [= initializer];

THE & OPERATOR The address operator & yields the address of its operand. If the operand x has the type T, then the expression &x has the type pointer to T The operand of the address operator must have an addressable location in memory: the operand must designate either a function or an object (i.e., an lvalue) that is not a bit-field. You need to obtain the addresses of objects and functions when you want to initialize pointers to them: float x, *ptr; ptr = &x; ptr = &(x+1); // OK: Make ptr point to x. // Error: (x+1) is not an lvalue.

THE INDIRECTION OPERATOR * Conversely, when you have a pointer and want to access the object it references, use the indirection operator *, which is sometimes called the dereferencing operator. Its operand must have a pointer type. If ptr is a pointer, then *ptr designates the object or function that ptr points to. If ptr is an object pointer, then *ptr is an lvalue, and you can use it as the left operand of an assignment operator: float x, *ptr = &x; *ptr = 1.7 ++(*ptr); // Assign the value 1.7 to the variable x // and add 1 to it.

INDIRECTION AND ARITHMETIC Asterisk * with one operand is the dereference or indirection operator, and with two operands, it is the multiplication sign. In each of these cases, the unary operator has higher precedence than the binary operator. For example, the expression *ptr1 * *ptr2 is equivalent to (*ptr1) * (*ptr2). Look at the operator precedence/associativity table

QUESTION Given üint *p= NULL; What is its type of p? üint? NO: its type is pointer to int or int*

IN MEMORY The addresses shown are purely fictitious examples. int ivar = 77; int *iptr = &ivar; Variable ivar iptr Value in memory 77 1000 Address 1000 1004

PRINT POINTERS It is often useful to output addresses for verification and debugging purposes. üthe printf( ) functions provide a format specifier for pointers: %p. printf( "Value of iptr (i.e. the address of ivar): %p\n" "Address of iptr: %p\n", iptr, &iptr ); The size of a pointer in memory given by the expression sizeof(iptr), for example is the same regardless of the type of object addressed. 8 byte(?)

NULL POINTERS A null pointer constant is an integer constant expression with the value 0. The macro NULL is defined in stdlib.h. A null pointer is always unequal to any valid pointer to an object or function.

EXAMPLE Initialization üint *p = NULL; #include <stdlib.h> int main() { int a= 3; int* p= NULL; *p= 6; } #include <stdio.h> int main() { int a= 3; int* p= &a; *p= 6; } Segmentation fault

VOID POINTERS A pointer to void, or void pointer for short, is a pointer with the type void *. As there are no objects with the type void, the type void * is used as the all-purpose pointer type. üa void pointer can represent the address of any object but not its type. To access an object in memory, you must always convert a void pointer into an appropriate object pointer. void* pa= NULL; int p= 10; pa= &p; printf("%d", *((int*) pa));

POINTERS TO POINTERS A pointer variable is itself an object in memory, which means that a pointer can point to it. To declare a pointer to a pointer, you must use two asterisks üchar c = 'A', *cptr = &c, **cptrptr = &cptr; The expression *cptrptr now yields the char pointer cptr, and the value of **cptrptr is the char variable c. cptrptr cptr c &cptr &c A

EXAMPLE The address of a is 0x7fff4fca4acc int main(){ int a= 2, *p= &a; printf("%d %d\n", *p, *&*&a); printf("%p %p\n", p, &*&a); } MacBook-Francesco:ProgrammI francescosantini$./main 2 2 0x7fff4fca4acc 0x7fff4fca4acc

OPERATIONS WITH POINTERS

READ AND MODIFY If ptr is a pointer, then *ptr designates the object (or function) that ptr points to. The type of the pointer determines the type of object that is assumed to be at that location in memory. For example, when you access a given location using an int pointer, you read or write an object of type int.

EXAMPLES double x, y, *ptr; // Two double variables and a pointer to double. ptr = &x; // Let ptr point to x. *ptr = 2.5; // Assign the value 2.5 to the variable x. *ptr *= 2.0; // Multiply x by 2. y = *ptr + 0.5; // Assign y the result of the addition x + 0.5. x is equal to 5.0 y is equal to 5.5

QUESTIONS int a= 3, *p= &a; üis a an lvalue? üis p an lvalue? üis *p an lvalue? üis &a an lvalue? Yes Yes Yes No int a= 3; int* p= &a, *q = p; p == q &a == 1000 a p q 3 1000 1000 1000 1004 1012

OPERATIONS The most important of these operations is accessing the object that the pointer refers to You can also ücompare pointers, and üuse them to iterate through a memory block Pointer arithtmetics

POINTER ARITHMETICS When you perform pointer arithmetic, the compiler automatically adapts the operation to the size of the objects referred to by the pointer type. You can perform the following operations on pointers to objects: üadding an integer to, or subtracting an integer from, a pointer. üsubtracting one pointer from another. ücomparing two pointers.

EXAMPLE ON COMPARING int main() { int a= 5; int *p= &a; int *q= &a; } if (p == q) printf( The two pointers are the same ); Comparison (== and!=) is used to check if two pointers point to the same location of memory

ARITHMETIC AND ARRAY OPERATIONS The three pointer operations described here are generally useful only for pointers that refer to the elements of an array. To illustrate the effects of these operations, consider two pointers p1 and p2, which point to elements of an array a: üif p1 points to the array element a[i], and n is an integer, then the expression p2 = p1 + n makes p2 point to the array element a[i+n] (assuming that i+n is an index within the array a). üthe subtraction p2 p1 yields the number of array elements between the two pointers, with the type ptrdiff_t. The type ptrdiff_t is defined in the header file stddef.h, usually as int. After the assignment p2 = p1 + n, the expression p2 p1 yields the value of n. üthe comparison p1 < p2 yields true if the element referenced by p2 has a greater index than the element referenced by p1. Otherwise, the comparison yields false.

EXAMPLE // Initialize an array and a pointer to its first element. int darr[5] = { 2, 1, 6, 3, 4 }, *dptr = darr; int i = 0; dptr = dptr + 1; dptr = 2 + dptr; printf( "%d\n", *dptr ); printf( "%d\n", *(dptr -1) ); 3 6 3 i = dptr - darr; printf( %d\n", i ); darr 2 1 6 3 4 dptr dptr dptr

CONSIDERATIONS ON THE EXAMPLE The statement dptr = dptr + 1; adds the size of one array element to the pointer, so that dptr points to the next array element, darr[1]. Because dptr is declared as a pointer to int, its value is increased by sizeof(int). Subtracting one pointer from another yields an integer value with the type ptrdiff_t. The value is the number of objects that fit between the two pointer values. üthe type ptrdiff_t is defined in the header file stddef.h, usually as int.

MORE ON ARRAYS Because the name of an array is implicitly converted into a pointer to the first array element wherever necessary, you can also substitute pointer arithmetic for array subscript notation: üthe expression a + i is a pointer to a[i], and the value of *(a+i) is the element a[i]. üarrays do not exist in C : they are just pointers

L VALUES AND POINTERS The operators that yield an lvalue include the subscript operator [] and the indirection operator *

ONE MORE EXAMPLE #include <stdio.h> int main() { // Initialize an array and a pointer to its first element. int darr[5] = { 2, 1, 6, 3, 4 }, *dptr = darr; } int i = 0; dptr = dptr + 1; printf("darr %p\n", darr); printf( dptr %p\n", dptr); dptr = 2 + dptr; printf( dptr %p\n", dptr); darr 0x7fff56845b19 dptr 0x7fff56845b1d dptr 0x7fff56845b25

AN ADVANCED EXAMPLE *a == a[0] p == a == &a[0] Little endian int main() { short int a[4]= {1,3,[3]=1}; int *p = (int*) a; } printf("*a is equal to %d\n", *a); printf("*p==0 %d\n", *p== 0); a + 2 printf("p == a %d\n", p == a); printf("*(a+2) == 0 %d\n", *(a+2) == 0); p + 1 printf("*(p+1)== 65536 %d\n", *(p+1) == 65536); printf("&a[3] > (p + 1) %d\n", &a[3] > p+1); printf("%ld\n", (a+2)- &a[0]); printf("%d\n", ((int) (a+2)) - (int) (&a[0]) ); *(p + 1) A short int is 2 bytes, an int is 4 bytes &a[3] *p *a *(a+2) 1000 10000000 1001 00000000 1002 11000000 1003 00000000 1004 00000000 1005 00000000 1006 10000000 1007 00000000 1008 1x 2 16 + 1 x 2 17 + 1 x 2 0 = 196609

EXAMPLE int main() { short int a[4]= {1,3,[3]=1}; int *p = (int*) a; } printf("*p is equal to %d\n", *a); printf("*p == 0 %d\n", *p== 0); printf("p == a %d\n", p == a); printf("*(a+2)= %d\n", *(a+2) == 0); printf("*p == 65536 %d\n", *(p+1) == 65536); printf("&a[3] > (p+1) %d\n", &a[3]> (p+1)); printf("%ld\n", (a+2) - &a[0]); printf("%d\n", ((int) (a+2)) - (int) (&a[0]) ); MacBook-Francesco:esercizi francescosantini$./main *p is equal to 1 *p == 0 0 p == a 1 *(a+2)== 0 1 *p == 65536 1 &a[3] > (p+1) 1 2 4

CONST POINTERS AND POINTERS TO CONST

CONSTANT POINTERS AND POINTERS TO CONSTANT OBJECTS It is possible to also define constant pointers. When you define a constant pointer, you must also initialize it, because you can t modify it later. int var, var2; // Two objects with type int. int *const c_ptr = &var; // A constant pointer to int. *c_ptr = 123; // OK: we can modify the object referenced, but... c_ptr= &var2; // error: we can't modify the pointer.

POINTERS TO CONST You can modify a pointer that points to an object that has a const-qualified type (also called a pointer to const). However, you can use such a pointer only to read the referenced object, not to modify it üfor this reason, pointers to const are commonly called readonly pointers. You can use them if you want to be sure to not modify a variable through its pointer

EXAMPLE int var; const int c_var = 100; const int *ptr_to_const; ptr_to_const = &c_var; var = 2 * *ptr_to_const; ptr_to_const = &var; if ( c_var < *ptr_to_const ) *ptr_to_const = 77; // An object with type int. // A constant int object. // A pointer to const int: // the pointer itself is not constant! // OK: Let ptr_to_const point to c_var. // OK. Equivalent to: var = 2 * c_var; // OK: Let ptr_to_const point to var. // OK: "read-only" access. // Error: we can't modify var using // ptr_to_const, even though var is // not constant. The assignment ptr_to_const = &var entails an implicit conversion: the int pointer value &var is automatically converted to the left operand s type, pointer to const int.

ONE MORE EXAMPLE If you want to convert a pointer into a pointer to a lessqualified type, you must use an explicit type conversion. int var; const int c_var = 100, *ptr_to_const; int *ptr = &var; *ptr = 77; ptr_to_const = ptr; *ptr_to_const = 77; ptr = &c_var; ptr = (int *) &c_var; // An int pointer that points to var. // OK: ptr is not a read-only pointer. // OK: implicitly converts ptr from "pointer to int // into "pointer to const int". // Error: can't modify a variable through a read-only // pointer. // Error: can't implicitly convert "pointer to const // int" into "pointer to int". // OK: Explicit pointer conversions are always // possible.