Faculty of Engineering
Computer Engineering Department
Islamic University of Gaza
C++ Programming Language Lab # 12
Pointers and C-Strings
Objective:
To be familiar with C++ Programming Language.
The & and * Operators:
A pointer is a variable which stores the address of another variable. There are two important operators when working with pointers in C++: the address of (&) operator and the value of (*) operator.
Finding Out What Is Stored in Pointers:
Using a pointer to print the contents of the array:
Allocating and deleting a pointer:
A dynamic variable is a variable that is stored in the heap, outside the data and stack segments, that may change size during runtime or may even disappear for good. In fact if we do not allocate a certain amount of memory to store its contents, it will never exist.
If you decided to erase the dynamic variable from the heap. Use the delete operator .
while we have freed bytes of memory , the pointer was not erased. It still exists in the data or stack segment of the application and we may use it to initialize another dynamic variable.
Manually create a call-by-reference using a pointer:
Characters and C-Strings:
A string is a sequence of characters. There are two ways to process strings in C++. One way is to treat strings as arrays of characters. This is known as pointer-based strings or C-strings. The other way is to process strings using the string class.
Storing and Accessing Strings:
A pointer-based string in C++ is an array of characters ending in the null terminator ('\0'), which indicates where a string terminates in memory. An array can be accessed via a pointer. So a string can also be accessed via a pointer, which points to the first character in the string. So you can declare a string variable using an array or a pointer.
char city[7] = "Dallas";
char *pCity = "Dallas";
Returning Pointers from Functions:
You can use pointers as parameters in a function and you can return a pointer from a function.
String Functions:
Reading Strings:
v You can read a string from the keyboard using the cin object.
v C++ provides the cin.getline function in the iostream header file, which reads a string into an array. The syntax of the function is:
cin.getline(char array[], int size, char delimitChar).
Lab work:
v Apply the programming exercises practically on DEV C++ Program , and show the results to your instructor.
6