Pointers, Arrays and C-Strings

Similar documents
C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay

Homework #3 CS2255 Fall 2012

Pointers, Dynamic Data, and Reference Types

Classes - 2. Data Processing Course, I. Hrivnacova, IPN Orsay

Reference operator (&)

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):

Modern C++ for Computer Vision and Image Processing. Igor Bogoslavskyi

PIC 10A Pointers, Arrays, and Dynamic Memory Allocation. Ernest Ryu UCLA Mathematics

Input and Output. Data Processing Course, I. Hrivnacova, IPN Orsay

BITG 1113: POINTER LECTURE 12

Outline. Introduction. Arrays declarations and initialization. Const variables. Character arrays. Static arrays. Examples.

Input And Output of C++

Outline. Introduction. Pointer variables. Pointer operators. Calling functions by reference. Using const with pointers. Examples.

[0569] p 0318 garbage

12. Pointers Address-of operator (&)

Agenda. The main body and cout. Fundamental data types. Declarations and definitions. Control structures

CHAPTER 3 BASIC INSTRUCTION OF C++

A First Program - Greeting.cpp

Pointer Arithmetic. Lecture 4 Chapter 10. Robb T. Koether. Hampden-Sydney College. Wed, Jan 25, 2017

C++ ARRAYS POINTERS POINTER ARITHMETIC. Problem Solving with Computers-I

Name MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

Looping and Counting. Lecture 3 Hartmut Kaiser hkaiser/fall_2012/csc1254.html

Looping and Counting. Lecture 3. Hartmut Kaiser hkaiser/fall_2011/csc1254.html

CS2141 Software Development using C/C++ C++ Basics

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

Pointers. Memory. void foo() { }//return

Pointers. Reference operator (&) ted = &andy;

CSE 307: Principles of Programming Languages

! Pass by value: when an argument is passed to a. ! It is implemented using variable initialization. ! Changes to the parameter in the function body

The C++ Language. Arizona State University 1

C++ Strings, Enums. Data Processing Course, I. Hrivnacova, IPN Orsay

CSC 211 Intermediate Programming. Arrays & Pointers

CS2255 HOMEWORK #1 Fall 2012

Pointers. Variable Declaration. Chapter 10

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

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements

Chapter 2: Introduction to C++

Chapter 2: Special Characters. Parts of a C++ Program. Introduction to C++ Displays output on the computer screen

! A program is a set of instructions that the. ! It must be translated. ! Variable: portion of memory that stores a value. char

Object-Oriented Programming for Scientific Computing

THE GOOD, BAD AND UGLY ABOUT POINTERS. Problem Solving with Computers-I

CS162 - POINTERS. Lecture: Pointers and Dynamic Memory

PART I. Part II Answer to all the questions 1. What is meant by a token? Name the token available in C++.

Scott Gibson. Pointers & Dynamic Memory. Pre & Co Requisites. Random Access Memory. Data Types. Atomic Type Sizes

Outline. 1 Function calls and parameter passing. 2 Pointers, arrays, and references. 5 Declarations, scope, and lifetimes 6 I/O

pointers + memory double x; string a; int x; main overhead int y; main overhead

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

Pointers and References

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Chapter 2: Basic Elements of C++

6.096 Introduction to C++ January (IAP) 2009

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

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

CS31 Discussion 1E Spring 17 : week 08

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

Exercise 1.1 Hello world

Object-Oriented Programming, Classes

2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program

Pointers. 1 Background. 1.1 Variables and Memory. 1.2 Motivating Pointers Massachusetts Institute of Technology

Short Notes of CS201

CSI33 Data Structures

CSCI-1200 Data Structures Fall 2017 Lecture 5 Pointers, Arrays, & Pointer Arithmetic

REVIEW. The C++ Programming Language. CS 151 Review #2

Week 3. Function Definitions. Example: Function. Function Call, Return Statement. Functions & Arrays. Gaddis: Chapters 6 and 7.

Functions, Arrays & Structs

calling a function - function-name(argument list); y = square ( z ); include parentheses even if parameter list is empty!

CS201 - Introduction to Programming Glossary By

More about BOOLEAN issues

Agenda. The main body and cout. Fundamental data types. Declarations and definitions. Control structures

CMSC 202 Midterm Exam 1 Fall 2015

CS101: Fundamentals of Computer Programming. Dr. Tejada www-bcf.usc.edu/~stejada Week 6: Pointers

Exam 3 Chapters 7 & 9

LECTURE 02 INTRODUCTION TO C++

Cours de C++ Introduction

FORM 2 (Please put your name and form # on the scantron!!!!)

Kingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS242 ARRAYS

Pointers. Lecture 2 Sections Robb T. Koether. Hampden-Sydney College. Fri, Jan 18, 2013

Introduction to Programming using C++

15. Pointers, Algorithms, Iterators and Containers II

Managing Memory. (and low level Data Structures) Lectures 22, 23. Hartmut Kaiser.

CS31 Discussion. Jie(Jay) Wang Week8 Nov.18

Basic program The following is a basic program in C++; Basic C++ Source Code Compiler Object Code Linker (with libraries) Executable

04-24/26 Discussion Notes

Chapter 1 INTRODUCTION

CSc Introduction to Computing

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

Pointers. Lecture 2 Sections Robb T. Koether. Hampden-Sydney College. Mon, Jan 20, 2014

Computer Programming : C++

OBJECT ORIENTED PROGRAMMING

CSCE 206: Structured Programming in C++

CSCE 206: Structured Programming in C++

Professor Terje Haukaas University of British Columbia, Vancouver C++ Programming

CS 103 Unit 13 Slides

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

Review. Outline. Array Pointer Object-Oriented Programming. Fall 2013 CISC2200 Yanjun Li 1. Fall 2013 CISC2200 Yanjun Li 2

Computer Systems Principles. C Pointers

Structured Programming Using C++ Lecture 2 : Introduction to the C++ Language. Dr. Amal Khalifa. Lecture Contents:

Review. Outline. Array Pointer Object-Oriented Programming. Fall 2017 CISC2200 Yanjun Li 1. Fall 2017 CISC2200 Yanjun Li 2

Variables. Data Types.

Transcription:

Pointers, Arrays and C-Strings Data Processing Course, I. Hrivnacova, IPN Orsay Variable in Memory Pointers Nullptr Pointers vs References C-Arrays C-Strings Problems with C-Arrays, C-Strings 1

Variables in Memory A computer memory location has an address and holds a content. The address is a numerical number (often expressed in hexadecimal), which is hard for programmers to use directly. Typically, each address location holds 8-bit (i.e., 1byte) of data. Chua Hock-Chuan: Programming Notes 2

Variables in Memory A variable is a named location that can store a value of a particular type. Names (or identifiers) are attached to certain addresses. Types (such as int, double, char) are associated with the contents for ease of interpretation of data. int sum = 255; sum: 255 Chua Hock-Chuan: Programming Notes 3

Pointers Pointer = an object that refers to another object The pointer value = the address of the object pointed The pointer type - formed by the type of the pointed object and * Ex. int*, float * int sum = 255; sum: 255 ptrsum: Chua Hock-Chuan: Programming Notes 4

Pointers int number = 88; int* pnumber = &number; cout << pnumber<< endl; cout << *pnumber << endl; Pointer type: int* Address operator: & *pnumber = 99; cout << *pnumber << endl; cout << number << endl; number: 255 Gives a variable address Derefence operator: * Indirectly give the variable pointed by the pointer pnumber: 5

Using Pointers int number = 88; int* pnumber = &number; cout << pnumber<< endl; cout << *pnumber << endl; *pnumber = 99; cout << *pnumber << endl; cout << number << endl; number: 255 pnumber: Program output: >./testpointers 0x7fff5a4b8c9c 88 99 99 6

Not Initialized Pointers (!) int* pnumber ; *pnumber = 55; cout << *pnumber << endl; Program output: >./testpointers Segmentation fault: 11 The pointer pnumber was declared without initialization i.e., it is pointing to "somewhere" which is of course an invalid memory location. The *pnumber = 55 corrupts the value of "somewhere"! 7

nullptr int* pnumber = nullptr; if ( pnumber ) { *pnumber = 55; cout << *pnumber << endl; } The special constant nullptr denotes a pointer which points nowhere It corresponds to boolean value false,and all other values to true We can test pointers logically 8

References A reference = is an alias, or an alternate name to an existing variable. Reference declaration: the type of object and & Ex. int&, float& int sum = 255; int& refsum = sum; You need to initialize the reference during declaration. int& ir; //!! error int& ir = nullptr; //!! error Referencing and dereferencing are done on the references implicitly. sum: refsum: References are NOT pointers No explicit dereferencing operator * and address-of operator & should be used as it is in case of pointers References are feature of C++ 9

#include <iostream> using namespace std; int main() { int number = 88; int* ptrnumber = int& refnumber = cout << "number: cout << "number: cout << "number: References vs. Pointers &number; number; " << number << endl; " << *ptrnumber << endl; " << refnumber << endl; // 88 // 88 // 88 int number2 = 99; ptrnumber = &number2; cout << "number2: " << number2 << endl; // 99 cout << "number2: " << *ptrnumber << endl; // 99 The reference acts as another name of the object, it can not be changed to point to another object, it does not occupy memory space refnumber = number2; } //!!! will set the value // of 'number2' to 'number' cout << "refnumber: " << refnumber << endl; // 99 cout << "number: " << number << endl; // 99 10

Arrays An array is a collection of several elements of the same type, arranged in a sequence Arrays are created (declared) with brackets Element access via operator [] Their index ranges from 0 to size -1 // Declare and initialize an int array of 6 elements int a[6] = {11, 22, 33, 44, 55, 66}; Chua Hock-Chuan: Programming Notes 11

Arrays & Pointers Arrays can be accessed using pointers. An array variable, a, is actually a pointer to the first element of the array // Declare and initialize an int array of 6 elements int a[6] = {11, 22, 33, 44, 55, 66}; int* ptra = a; // Modify first element a: *ptra = 77; Chua Hock-Chuan: Programming Notes 12

Pointer Arithmetics Pointers can move around all elements of an array: If an integer n is added to the pointer, the pointer is increased by n elements. The ++ operator increases by one element If we sum the pointer value and an integer n, the result points tp the nth value after the pointer If we subtract two pointers, we get the distance between the elements to which they point int numbers[6] = {11, 22, 33, 44, 55, 66}; for ( int* ptr = numbers; ptr < numbers + 6; ++ptr ) { cout << *ptr << endl; } 13

Range-based for loop Can be also used in the context of an array int numbers[6] = {11, 22, 33, 44, 55, 66}; for ( int number : numbers ) { cout << number << endl; } 14

Problems with Arrays Pitfall of C(C++): C/C++ does not perform array index-bound check. In other words, if the index is beyond the array's bounds, it does not issue a warning/error. Handling of the arrays can be dangerous, you should prefer use of vectors or std::arrays (since C++11) int numbers[6] = {11, 22, 33, 44, 55, 66}; // Index out of bound! // Can compiled and run, but could pose very serious side effect! numbers[88] = 999; cout << numbers[77] << endl; 15

C-Strings The standard string types of C++ encapsulate the details of the low-level string processing In C, strings are managed as arrays of characters with the '\0' character at the end. The length of a C-string is the number of characters until '\0' The string literals ("hello") have this low-level format, their type is const char* const means that characters cannot be changed hello : h e l l o \0 16

Problems with C-Strings const char* s = "hello"; const char* t = "Nico"; s : h e l l o \0 t : N i c o \0 h e l l o \0 t : N i c o \0 Assigns pointers rather than characters Special functions have to be used for operations with C-Strings s = t; s : to copy, compare, etc. The same danger of out of bound errors as for arrays You should prefer use of std::string 17