Presentation is loading. Please wait.

Presentation is loading. Please wait.

Array & Pointers CSCE 121 J. Michael Moore.

Similar presentations


Presentation on theme: "Array & Pointers CSCE 121 J. Michael Moore."— Presentation transcript:

1 Array & Pointers CSCE 121 J. Michael Moore

2 Arrays We’ve avoided them so far preferring to use vectors
Frequently are pointers. No bounds checking. Arrays do not know their sizes.

3 Array Offsets / Indexing
int ary[20]; Defines a pointer and memory large enough for 20 integers. ary[index] *(address of first element + index * size of type) ary[15] *(address of first element + 15 * size of type)

4 Array Offsets / Indexing
int ary[20]; cout << "address of first element: " << &ary[0] << endl; cout << "address of ary: " << &ary << endl; cout << "value in ary: " << ary << endl; cout << "address of 5th element: " << &ary[4] << endl; cout << "address of 5th element: " << ary + 4 << endl; cout << "value of 5th element: " << ary[4] << endl; Pointer arithmetic.

5 char* f() { char ch[20]; char* p = &ch[90]; // ... *p = 'a'; // we don’t know what this will overwrite char* q; // forgot to initialize *q = 'b'; // we don’t know what this will overwrite return &ch[10]; // Oops! ch disappears upon return // from f(); an infamous “dangling pointer” } void g() { char* pp = f(); *pp = 'c'; // we don’t know what this will overwrite; // f’s ch is gone after f’s return

6 cstring An array of char. Fixed size.
Last character must be followed by ‘\0’. Reading cstring continues until it finds ‘\0’. If ‘\0’ not included in string, will read until??? Same problems with arrays. Where have we seen cstrings???

7 So Why Bother with Arrays?
They are all that C has lots of C code “out there” (billions of lines) lots of C++ code in C style (hundreds of millions of line) You’ll eventually encounter code full of arrays and pointers They represent primitive memory in C++ programs we need them (mostly on free store allocated by new) to implement better container types, like vector Avoid arrays whenever you can largest single source of bugs in C and (unnecessarily) in C++ programs among the largest sources of security violations, usually (avoidable) buffer overflows

8 Acknowledgement Including slides created by Bjarne Stroustrup and Jennifer Welch


Download ppt "Array & Pointers CSCE 121 J. Michael Moore."

Similar presentations


Ads by Google