Pointers and Data Files
Pointers and Data Files
This domain tests address manipulation and file handling. A pointer stores an address: int *p = &x; makes p hold the address of x; *p dereferences it. Pointer arithmetic moves by the size of the pointed-to type. new allocates from the free store and delete releases it; use delete[] for arrays. A null pointer points to nothing and must not be dereferenced.
Files
Include the fstream header. ofstream writes, ifstream reads, fstream does both. Open with a mode such as ios::out, ios::in or ios::app; check is_open(); read with >> or getline; close with close(). Text files store characters; binary files store raw bytes.
Worked example
int x = 10; int *p = &x; *p = 20; cout << x; prints 20. p holds the address of x, so changing *p changes the same memory that x names. For a file, an ofstream object opens a text file, writes 25 and closes it; reading the file back into an int gives 25. If the file fails to open, extraction fails.
Traps
An uninitialized pointer is not automatically null. Do not delete the same block twice. delete on a pointer to a local variable is an error. getline reads a whole line, while >> stops at whitespace. Always close a file before reopening it for reading.