Указатели, масиви и структури Доц. д-р Владимир Димитров Web: cht_co.tripod.com Wap:

Slides:



Advertisements
Similar presentations
Numerical Recipes The Art of Scientific Computing (with some applications in computational physics)
Advertisements

C++ crash course Class 10 practice problems. Pointers The following function is trying to swap the contents of two variables. Why isnt it working? void.
Dynamic Allocation and Linked Lists. Dynamic memory allocation in C C uses the functions malloc() and free() to implement dynamic allocation. malloc is.
C’ POINTERS Basic&Examples. Q:what’s the output? int array[] = { 45, 67, 89 }; int *array_ptr = array; printf(" first element: %i\n", *(array_ptr++));
Brown Bag #2 Advanced C++. Topics  Templates  Standard Template Library (STL)  Pointers and Smart Pointers  Exceptions  Lambda Expressions  Tips.
Introduction to Programming Lecture 15. In Today’s Lecture Pointers and Arrays Manipulations Pointers and Arrays Manipulations Pointers Expression Pointers.
LECTURE 17 C++ Strings 18. 2Strings Creating String Objects 18 C-string C++ - string \0 Array of chars that is null terminated (‘\0’). Object.
Introduction to Programming Lecture 39. Copy Constructor.
Templated Functions. Overloading vs Templating  Overloaded functions allow multiple functions with the same name.
1 Chapter 10 Strings and Pointers. 2 Introduction  String Constant  Example: printf(“Hello”); “Hello” : a string constant oA string constant is a series.
String in C++. String Series of characters enclosed in double quotes.“Philadelphia University” String can be array of characters ends with null character.
1 Class Vehicle #include #define N 10../.. 2 Class Vehicle class vehicle { public: float speed; char colour[N+1]; char make[N+1];
By Senem Kumova Metin 1 POINTERS + ARRAYS + STRINGS REVIEW.
1 Arrays Chapter 9. 2 Outline  The array structure (Section 9.1)  Array declaration  Array initialization  Array subscripts  Sequential access to.
This Time Pointers (declaration and operations) Passing Pointers to Functions Const Pointers Bubble Sort Using Pass-by-Reference Pointer Arithmetic Arrays.
Pointer, malloc and realloc 1. Name entered was 6 char, not enough space to put null terminator 2 Array of char.
Surviving C and PostgreSQL CS186 Supplemental Session 9/13/04 Matt Denny, Paul Huang, Murali Rangan (Originally prepared by Shariq Rizvi, Wei Xu, Shawn.
Pointer What it is How to declare it How to use it Relationship between arrays and pointers Relationship between strings and pointers.
 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays –Structures of related data items –Static entity (same size throughout program) A few types –Pointer-based.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
Pointers Example Use int main() { int *x; int y; int z; y = 10; x = &y; y = 11; *x = 12; z = 15; x = &z; *x = 5; z = 8; printf(“%d %d %d\n”, *x, y, z);
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
 2007 Pearson Education, Inc. All rights reserved C Pointers.
Dynamic Memory Allocation. Domain A subset of the total domain name space. A domain represents a level of the hierarchy in the Domain Name Space, and.
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.
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.
Pointer Arithmetic CSE 2541 Rong Shi. Pointer definition A variable whose value refers directly to (or "points to") another value stored elsewhere in.
CSC241 Object-Oriented Programming (OOP) Lecture No. 6.
Copyright 2005, The Ohio State University 1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation.
Pointers A pointer is a variable that contains a memory address as it’s value. The memory address points to the actual data. –A pointer is an indirect.
Lecture 6 C++ Programming Arne Kutzner Hanyang University / Seoul Korea.
Data Types Declarations Expressions Data storage C++ Basics.
Introduction to C Programming Lecture 6. Functions – Call by value – Call by reference Arrays Today's Lecture Includes.
Integer Types short month; // half of a machine word int car; // one machine word unsigned long distance; Character Types char c = ‘\0’; // one byte char.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter Array Basics.
System Programming Practical Session 7 C++ Memory Handling.
Charles Clute Tom Most Michael Hein. Strings in C  There is no String... But there’s hope! Strings are character arrays char volume[6]; char volume[6]
1 Object-Oriented Programming Using C++ A tutorial for pointers.
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).
The Basics of Arrays Problem: How can the rancher easily catalog all of his cattle?
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.
Object Oriented Programming in C++ Chapter 7 Dynamic Binding.
 Memory setup  Pointer declaration  Address operator  Indirection  Printing addresses or pointers.
CHAPTER 07 Arrays and Vectors (part II). OBJECTIVES In this part you will learn:  To pass arrays to functions.  Basic searching techniques.
1 A Pointer: an address, a reference, a location of the computer memory A pointer of what? int, char, bool, double, or any kind of data type need to know.
Array and Pointers An Introduction Unit Unit Introduction This unit covers the usage of pointers and arrays in C++
1 Lecture 4: Part1 Arrays Introduction Arrays  Structures of related data items  Static entity (same size throughout program)
Current Assignments Project 3 has been posted, due next Tuesday. Write a contact manager. Homework 6 will be posted this afternoon and will be due Friday.
Introduction to Programming Lecture 12. Today’s Lecture Includes Strings ( character arrays ) Strings ( character arrays ) Algorithms using arrays Algorithms.
Pointers. Introduction to pointers Pointer variables contain memory addresses as their values. Usually, a variable directly contains a specific value.
Basic Concepts:- Invalid use of Address Operator &75 &(‘a’) &(a+b)
Pointers Pointers are variables that contain memory addresses as their values. A variable directly contains a specific value. A pointer contains an address.
C++ Programming Lecture 18 Pointers – Part II The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
The C++ Data Types Fundamental Data Types
Characters and Strings
Introduction to Programming
Pointers and Pointer-Based Strings
Programming -2 برمجة -2 المحاضرة-5 Lecture-5.
Pointers, Dynamic Data, and Reference Types
Default Arguments.
Dynamic Memory A whole heap of fun….
CS111 Computer Programming
Pointers Lecture 1 Thu, Jan 15, 2004.
Introduction to Programming
Function Overloading.
Pointers and Pointer-Based Strings
Arrays Arrays A few types Structures of related data items
The Stack.
Characters and Strings
Presentation transcript:

Указатели, масиви и структури Доц. д-р Владимир Димитров Web: cht_co.tripod.com Wap:

Съдържание 1. Указатели 1. Нула 2. Масиви 1. Инициализация на масиви 2. Символни низове литерали 3. Указатели в масиви 1. Навигация в масиви 4.Константи 1.Указатели и константи 5.Референси 6.Указател към void 7.Структури 1.Еквивалентност на типове 8.Съвети

Указатели 1 char c = ' a'; char* p = &c; // p holds the address of c p:&c c:'a'

Указатели 2 int* pi; // pointer to int char** ppc; // pointer to pointer to char int* ap [15]; // array of 15 pointers to ints int (*fp) (char*); // pointer to function taking a char* argument; returns an int int* f(char*); // function taking a char* argument; returns a pointer to int

Указатели 3 char c = ' a'; char* p = &c; // p holds the address of c char c2 = *p; // c2 == 'a' const int NULL = 0;

Масиви float v[3];// an array of three floats: v[0], v[1], v[2] char* a[32];// an array of 32 pointers to char: a[0].. a[31] void f(int i) { int v1[i];// error: array size not a constant expression vector v2 (i);// ok } int d2[10] [20];// d2 is an array of 10 arrays of 20 integers int bad[5,2]; // error: comma not allowed in a constant expression

Инициализация на масиви int v1[] = {1, 2, 3, 4}; char v2[] = {'a', 'b', 'c', 0}; char v3[2] = {'a', 'b', 0}; // error: too many initializers char v4[3] = {'a ', 'b', 0};// ok int v5[8] ={1, 2, 3, 4}; int v5[] = {1, 2, 3, 4, 0, 0, 0, 0}; void f() { v4 = {'c', 'd', 0};// error: no array assignment }

Символни низове литерали 1 "this is a string" sizeof("Bohr") == 5 void f() { char* p = " Plato"; p[4] = 'e'; // error: assignment to const; result is undefined } void f() { char p[] = "Zeno";// p is an array of 5 char p[0] = 'R';//ok }

Символни низове литерали 2 const char* error_message(int i) { //... return "range error"; } const char* p = "Heraclitus"; const char* q = "Heraclitus"; void g() { if (p == q) cout << "one'.\n"; // result is implementation-defined. //... }

Символни низове литерали 3 cout << "beep at end of message\a\n"; "this is not a string but a syntax error" char alpha[] = " abcdefghijklmnopqrstuvwxyz." "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

Указатели в масиви 1 int v[] = {1, 2, 3, 4} ; int* pi = v; // pointer to initial element (implicit conversion) int* p2 = &v[0]; // pointer to initial element int* p3 = &v[4]; // pointer to one beyond last element 1234 v: p1 p2p3

Указатели в масиви 2 extern "C" int strlen(const char*);// from void f() { char v[] = "Annemarie"; char* p = v;// implicit conversion of char[] to char* strlen(p); strlen(v); // implicit conversion of char[] to char* v = p; // error: cannot assign to array }

Навигация в масиви 1 void fi(char v[]) { for (int i=0; v[i] != 0; i++) use(v[i]); } void fp(char v[]) { for (char* p = v; *p != 0; p++) use (*p); }

Навигация в масиви 2 #include int main() { int vi[10]; short vs[10]; std::cout << &vi[0] << ' ' << &vi[1] << '\n'; std::cout << &vs[0] << ' ' << &vs[1] << '\n'; } 0x7fffaef0 0x7fffaef4 0x7fffaedc 0x7fffaede sizeof(short) == 2 sizeof(int) == 4

Навигация в масиви 3 void f() { int v1[10]; int v2[10]; int i1 = &v1[5] - &v1[3]; // i1 = 2 int i2 = &v1[5] - &v2[3]; // result undefined int* p1 = v2+2; // p1=&v2[2] int* p2 = v2-2; // *p2 undefined }

Навигация в масиви 3 void fp(char v[], unsigned int size) { for (int i=0; i<size; i++) use(v[i]); const int N = 7; char v2[N]; for (int i=0; i<N; i++) use(v2[i]); }

Константи 1 const int model = 90;// model is a const const int v[] = {1, 2, 3, 4};// v[i] is a const const int x;// error: no initializer void f() { model = 200; // error v[2]++; // error } void g (const X* p) {// can't modify *p here } void h() { X val; // val can be modified g(&val); //... }

Константи 2 const int c1 = 1; const int c2 = 2; const int c3 = my_f(3); // don't know the value ofc3 at compile time extern const int c4; // don't know the value of c4 at compile time const int* p = &c2; // need to allocate space for c2

Константи 3 const int a = 42; const int b = 99; const int max = 128; int v[max]; void f(int i) { switch(i) { case a: //... case a: //... }

Указатели и константи 1 void f1(char* p) { char s[] = "Gorm"; const char* pc = s; // pointer to constant pc[3] = 'g'; // error: pc points to constant pc = p; // ok char *const cp = s; // constant pointer cp[3] = 'a'; // ok cp = p; // error: cp is constant const char* const cpc = s; // const pointer to const cpc[3] = 'a'; // error: cpc points to constant cpc = p; // error: cpc is constant }

Указатели и константи 2 char *const cp; // const pointer to char char const* pc; // pointer to const char const char* pc2; // pointer to const char char* strcpy(char* p, const char* q); // cannot modify *q

Указатели и константи 3 void f4() { int a = 1; const int c = 2; const int* p1 = &c; // ok const int* p2 = &a; // ok int* p3 = &c; // error: initialization of int* with const int* *p3 = 7; // try to change the value of c }

Референси 1 void f() { int i = 1; int& r = i; // r and i now refer to the same int int x = r;// x = 1 r = 2;// i = 2 }

Референси 2 int i = 1; int& r1 = i;// ok: r1 initialized int& r2;// error: initializer missing extern int& r3;// ok: r3 initialized elsewhere

Референси 3 void g() { int ii = 0; int& rr = ii; rr++;// ii is incremented to 1 int* pp = &rr;// pp points to ii } pp:&ii rr: ii:1

Референси 4 double& dr = 1; // error: lvalue needed const double& cdr = 1; // ok double temp = double(1); // first create a temporary with the right value const double& cdr = temp; // then use the temporary as the initializer for cdr

Референси 5 void increment(int& aa) {aa++;} void f() { int x = 1; increment(x);// x = 2 }

Референси 6 int next(int p) { return p+1; } void incr(int* p} { (*p)++; } void g() { int x = 1; increment(x);// x = 2 x = next(x);// x = 3 incr(&x);// x = 4 }

Референси 7 struct Pair { string name; double val; }; vector pairs; double& value(const string& s) /* maintain a set of Pairs: search for s, return its value if found; otherwise make a new Pair and return the default value 0 */ { for (int i = 0; i < pairs.size(); i++) if (s == pairs[i].name) return pairs[i].val; Pair p = {s, 0}; pairs.push_back(p); // add Pair at end return pairs[pairs.size() - 1].val; }

Референси 8 int main() // count the number of occurrences of each word on input { string buf; while (cin b>> buf) value(buf)++; for (vector ::const_iterator p = pairs.begin(); p! = pairs.end(); ++p) cout name val << '\n '; } Вход: aa bb bb aa aa bb aa aa Изход: aa: 5 bb: 3

Указател към void void f(int* pi) { void* pv = pi; // ok: implicit conversion of int* to void* *pv; // error: can't dereference void* pv++; // error: can't increment void* // (the size of the object pointed to is unknown) int* pi2 = static_cast (pv); // explicit conversion back to int* double* pd1 = pv;// error double* pd2 = pi;// error double* pd3 = static_cast (pv);// unsafe } void* my_alloc(size_t n); // allocate n bytes from my special heap

Структури 1 struct address { char* name;// "Jim Dandy" long int number; // 61 char* street; // "South St" char* town; // "New Providence" char state[2]; // 'N' 'J' long up; // 7974 };

Структури 2 void f() { address jd; jd.name = "Jim Dandy" jd.number = 61; } address jd = { "Jim Dandy", 61, "South St", "New Providence", { 'N', ' J'}, 7974 };

Структури 3 void print_addr(address* p) { cout name << '\n ' number street << '\n ' town << '\n' state[0] state[J] zip << '\n'; }

Структури 4 address current; address set_current (address next} { address prev = current; current = next; return prev; }

Структури 5 struct Link { Link* previous; Link* successor; }; struct No_good { No_good member; // error: recursive definition };

Структури 6 struct List; // to be defined later struct Link { Link* pre; Link* suc; List* member_of; }; struct List { Link* head; };

Структури 7 class S; // 'S' is the name of some type extern S a; S f(); void g(S); S* h(S*); void k(S* p} { S a; // error: S not defined; size needed to allocate f(); // error: S not defined; size needed to return value g (a); // error: S not defined; size needed to pass argument p->m = 7; // error: S not defined; member name not known S* q = h[p]; // ok: pointers can be allocated and passed q->m = 7; // error: S not defined; member name not known }

Структури 8 struct stat {/*...*/}; int stat(char* name, struct stat* buf);

Еквивалентност на типове struct S1 { int a; }; struct S2 { int a; }; S1 x; S2 y = x; // error: type mismatch S1 x; int i = x; // error: type mismatch

Съвети 1. Избягвай нетривиална аритметика с указатели 2. Грижи се да не пишеш извън границите на масива 3. Използвай 0 вместо NULL 4. Използвай vector и valarray вместо вградените масиви (C-стил) 5. Използвай string вместо масиви от char завършващи с 0 6. Минимизирай използването на референсните аргументи 7. Избягвай void* - ползвай го само в код от ниско ниво 8. Избягвай нетривиалните литерали ("магичните числа") в кода. Вместо това дефинирай и използвай символни константи