This preview shows page 1. Sign up to view the full content.
Unformatted text preview: type, and is
equal to the number of objects of type the pointers are declared to point to that would fit
between where the two pointers point (fractional part discarded)
• Adding two pointers is illegal (and it doesn’t make any sense to do it)
p1 - 3 p1 - p2 // the address of the 3rd “double” cell in memory
// before the one p1 points to... this is a
// double* valued expression!
// the number of double-sized cells in memory
// between the one p2 points to and the one p1
// points to... this is an int-valued expression! p1 + p2 // illegal p2
0 1 p1
2 3 4 5 6 7 8 9 Scott B. Baden / CSE 100, Lec 2 / Spring 2013 10 11 ··· N-1
25 Other operators and pointers...
• These relational operators are defined for pointer arguments:
==, <, <=, >, >= • Pointer literal constants: nullptr is the “null pointer” of any type
nullptr was introduced in the C++11 standard
note that in a boolean context, the null pointer is interpreted as false, and any other
pointer value is interpreted as true • Unary ! operator:
For any pointer expression p,
!p is 1 if p is the null pointer; else 0 Scott B. Baden / CSE 100, Lec 2 / Spring 2013 26 Arrays and pointers in C and C++
• In C or C++, an array name acts like a const pointer to the first element of the array
• C arrays are always contiguous in memory: second element is right after the first, etc.
int* p; // create an array of 99 ints
// create a pointer-to-int p = a; // makes p points to the first element of a p = & a; // this also makes p point to first element of a a = p; // ERROR: p // array subscripts work on pointers...
// this is exactly the same as *(p + 3) *(a + 3) can’t assign to an array name, it’s const // and pointer arithmetic works on array names...
// this is exactly the same as a
// which is also exactly the same as
// (believe it or not!) Scott B. Baden / CSE 100, Lec 2 / Spring 2013 3[a] 27 Pitfalls with arrays and pointers in in C++
• With a declaration like
int a; expressions like a[-33] or a or *(a + 10000) are dubious
• However, these are not compiler errors, and may not even give you runtime errors
(unless they attempt to access protected memory)
• The power of pointer arithmetic can hurt you, if you’re not careful...
• For these reasons, though C-style arrays are available in C++, it is advisable to use data
structures from the Standard Template Library (STL) such as std::vector or
std::array instead of basic arrays Scott B. Baden / CSE 100, Lec 2 / Spring 2013 28 Today’s Lecture
• An introduction to C++
• Comparing Java and C++
• Basic C++ programming
• Avoid getting stuck by a pointer
• C++ primitive types and operators
• Reading: Weiss Ch 1, section 1.4 to 1.7 Scott B. Baden / CSE 100, Lec 2 / Spring 2013 29 Dynamic data bugs
• Automatic and static data is created and destroyed automatically. As a
View Full Document
- Spring '08
- Data Structures