Читайте также: |
|
Pointers must be declared before they can be used. The syntax of declaring a pointer is to place a * in front of the name. A pointer is associated with a type too.
type * ptr; // Declare a pointer variable called ptr as a pointer of typeFor example,
int *iPtr; // Declare a pointer variable called iPtr pointing to an int (an int pointer)double *dPtr; // Declare a double pointerTake note that you need to place a '*' in front of each pointer variable, in other words, '*' applies only to the name that followed. The '*' in the declaration statement is not an operator, but indicates that the name followed is a pointer variable. For example,
int *p1, *p2, i; // p1 and p2 are int pointers. i is an int.C supports two ways to pass a parameter to a function: call-by-value and call-by-pointer. C++ supports a third
parameter-passing mechanism: call-by-reference. The purpose of this section is to demonstrate how the three
parameter-passing mechanisms work and to help you understand which to use, when, and why.
Using functions we can structure our programs in a more modular way, accessing all the potential that structured programming can offer to us in C++.
#include <iostream.h>int addition (int a, int b){ int r; r=a+b; return (r);}int main (){ int z; z = addition (5,3); cout << "The result is " << z; return 0;}29) Pointers and strings in programming language C++.
A pointer is a variable whose value is the address of another variable. Like any variable or constant, you must declare a pointer before you can work with it. The general form of a pointer variable declaration is:
type *var-name;Here, type is the pointer's base type; it must be a valid C++ type and var-name is the name of the pointer variable. The asterisk you used to declare a pointer is the same asterisk that you use for multiplication. However, in this statement the asterisk is being used to designate a variable as a pointer. Following are the valid pointer declaration:
int *ip; // pointer to an integerdouble *dp; // pointer to a doublefloat *fp; // pointer to a floatchar *ch // pointer to characterThe actual data type of the value of all pointers, whether integer, float, character, or otherwise, is the same, a long hexadecimal number that represents a memory address. The only difference between pointers of different data types is the data type of the variable or constant that the pointer points to. There are few important operations which we will do with the pointers very frequently. (a) we define a pointer variables (b) assign the address of a variable to a pointer and (c) finally access the value at the address available in the pointer variable. This is done by using unary operator * that returns the value of the variable located at the address specified by its operand. Following example makes use of these operations:
#include <iostream> using namespace std; int main (){ int var = 20; // actual variable declaration. int *ip; // pointer variable ip = &var; // store address of var in pointer variable cout << "Value of var variable: "; cout << var << endl; // print the address stored in ip pointer variable cout << "Address stored in ip variable: "; cout << ip << endl; // access the value at the address available in pointer cout << "Value of *ip variable: "; cout << *ip << endl; return 0;}Stringthe C++ programming language, the std::string class is a standard representation for a string of text. This class alleviates many of the problems introduced by C-style strings by putting the onus of memory ownership on the string class rather than on the programmer. The class provides some typical string operations like comparison, concatenation, find and replace, and a function for obtaining substrings. It can be constructed from a C-style string, and a C-style string can also be obtained from it.#include <iostream>#include <string> int main(){ std::string foo = "fighters"; std::string bar = "stool"; // "!=" compares string contents for inequality, even though they are different objects. if (foo!= bar) { std::cout << "The strings are different." << std::endl; } // Prints "stool fighters" by creating a temporary object, which is automatically freed. std::cout << bar + " " + foo << std::endl; return 0;}Because a string may be stored by value, copying may take as long as O(n) (i.e., copying takes time proportional to the length of the string). It will also cause heap memory to be allocated, which is usually far more expensive than the copy. For that reason, string is generally passed by reference-to-const to avoid unnecessary copying: void print_the_string(const std::string& str){ std::cout << str;} To interoperate with C-interfaces, it is often necessary to obtain a null-terminated string from a basic_string. The c_str() member function yields a pointer to the first element of an array whose elements correspond to the bytes in the original string and this array has a 0 at the offset of the length. If the null terminator is not needed, the data() method returns the pointer without any work needed to make sure the 0 is there. If the string is modified or its lifetime ends, the pointers returned by these methods become invalid.
30) Dynamic memory allocation operations: new and delete.
C++ supports dynamic allocation and deallocation of objects using the new and delete operators. These operators allocate memory for objects from a pool called the free store. The new operator calls the special function operator new, and the delete operator calls the special function operator delete.
Beginning in Visual C++.NET 2002, the CRT's new function (in libc.lib, libcd.lib, libcmt.lib, libcmtd.lib, msvcrt.lib, and msvcrtd.lib) will continue to return NULL if memory allocation fails. However, the new function in the Standard C++ Library (in libcp.lib, libcpd.lib, libcpmt.lib, libcpmtd.lib, msvcprt.lib, and msvcprtd.lib) will support the behavior specified in the C++ standard, which is to throw a std::bad_alloc exception if the memory allocation fails.
Normally, if you #include one of the C++ standard headers, like <new>, you'll get a /defaultlib directive in your object that will reference the appropriate C++ Standard Library according to the CRT model you used (the /M* compiler options). Generally, that will cause the linker to use the throwing operator new from the C++ Standard Library instead of the nonthrowing one from the main CRT, because the order of defaultlib directives will cause libcp.lib to be searched before libc.lib (under /ML).
Even if you use one of the C++ standard library headers, it is possible to get non-throwing new. For example, compile the program below with the following command line and you will not get throwing new behavior, even though standard C++ header files are included:
// new_and_delete.cpp// compile with: /EHsc#include <stdio.h>#include <new>#include <limits.h>int main(){ int * i_arr; try { i_arr = new int[0x3fffffff]; } catch(...) { printf("caught exception\n"); } int * k_arr; k_arr = new (std::nothrow) int[0x3fffffff]; delete[] i_arr; // vector delete delete[] k_arr;}
Operators new and new[]
In order to request dynamic memory we use the operator new. new is followed by a data type specifier and -if a sequence of more than one element is required- the number of these within brackets []. It returns a pointer to the beginning of the new block of memory allocated. Its form is:
pointer = new type
pointer = new type [number_of_elements]
The first expression is used to allocate memory to contain one single element of type type. The second one is used to assign a block (an array) of elements of type type, where number_of_elements is an integer value representing the amount of these. For example:
int * bobby;
bobby = new int [5];
Operators delete and delete[]
Since the necessity of dynamic memory is usually limited to specific moments within a program, once it is no longer needed it should be freed so that the memory becomes available again for other requests of dynamic memory. This is the purpose of the operator delete, whose format is:
1 2 | delete pointer; delete [] pointer |
The first expression should be used to delete memory allocated for a single element, and the second one for memory allocated for arrays of elements.
The value passed as argument to delete must be either a pointer to a memory block previously allocated with new, or a null pointer (in the case of a null pointer, delete produces no effect).
Дата добавления: 2015-11-16; просмотров: 69 | Нарушение авторских прав
<== предыдущая страница | | | следующая страница ==> |
Continue Statement | | | Requirements for the robot |