List of key concepts from this chapter.
Pointers
A pointer is a value that represents the address of an object. Each object in your system has a unique memory address. For example if you have an object 'x' then '&x' is the address of x. And if p is the address of an object then *p is the value of that object.
Pointers to functions
In addition to pointing to objects, built-in and class types, you can also point to functions.
int (*fp)(int) // A pointer to a function that takes an int as a parameter
Now if we define a function with the same signature
int next(int n) { return n+1; }
Then the following will assign the pointer
fp = &next // or fp=next works as well
fp=next works above as well since you can only take an address from a function the '&' is implicit. Similarily you can call it either way:
fp(i);
(*fp)(i)
Arrays
An array is a basic container of same objects. int[3] for example. Arrays are not class types so they have no members.
You can initialize an array when you declare it, which is something you can't do with stl containers.
const int month_lengths[] = {31,28,31,30,31,30,31,31,30,31,30,31 };
Reading and Writing Files
You can write to standard error by using either cerr, or clog.
Example to copy file from one to another
int main() {
ifstream infile("in");
ifstream infile("out");
string s;
while(getline(infile,s))
outfile << s << endl
return 0;
}
Memory management
There are two distinct types of memory management: automatic and statically allocated.
Automatic memory managemt is associated with local variables. The system allocated memory when its first encountered and frees it with variable falls out of scope.
Statically allocated is associated with use of the 'static' keyword. For example
int* pointer_to_static() {
stataic int x;
return &x;
}
The third way is to allocate memory yourself from the heap through the keyword new.
int* p = new int(42);
No comments:
Post a Comment