Programming Fundamentals 12
Programming Fundamentals 12
PROGRAMMING
TOPIC: POINTERS
POINTERS
• In C++, pointers are variables that store the memory addresses of other variables.
ADDRESS IN C++
• If we have a variable var in our program, &var will give us its address in the memory. For
example,
• Here, 0x at the beginning represents the address is in the hexadecimal form.
• Notice that the first address differs from the second by 4 bytes and the second address
differs from the third by 4 bytes.
• As mentioned above, pointers are used to store addresses rather than values.
• int *pointVar;
• Note: The * operator is used after the data type to declare pointers.
ASSIGNING ADDRESSES TO POINTERS
If pointVar points to the address of var, we can change the value of var by using *pointVar.
For example
int var = 5;
int* pointVar;
// assign address of var
pointVar = &var;
// change value at address pointVar
*pointVar = 1;
cout << var << endl; // Output: 1
//Here, pointVar and &var have the same address, the value of var will also be changed when *pointVar is changed.
1. Import the iostream header file. This will allow us to use the functions defined in the header file without getting errors.
2. Include the std namespace to use its classes without calling it.
3. Call the main() function. The program logic should be added within the body of this function. The { marks the beginning
of the function’s body.
10. Print the address of variable x. The value of the address was stored in the variable ip.
1. Pointers are variables which store the address of other variables in C++.
2. More than one variable can be modified and returned by function using pointers.
3. Memory can be dynamically allocated and de-allocated using pointers.
4. Pointers help in simplifying the complexity of the program.
5. The execution speed of a program improves by using pointers.
SUMMARY