DATA STRUCTURE & ALGORITHMS Pointers & Structure
POINTERS IN C++ Pointers is an extremely powerful programming tool Make some things much easier, help improves program’s efficiency Possible to use pointers to dinamically allocate memory
WHAT ARE POINTERS? Pointers are just variables that store memory addresses, usually the addresses of other variable For example, in our daily life a pointer is like a safety deposit boxes that stored in another safety box
C++ POINTER SYNTAX Pointers require a bit of new syntax because when you have a pointer, you need the ability to request both the memory location it stores and the value stored at the memory location Pointer declaration: * ; For eg. u could declare a pointer that stores the address of an integer with the following syntax: int *points_to_integer;
POINTING TO SOMETHING To get the memory address of a variable (its location in memory), put the ‘&’ sign in front of the variable name. This is called the address-of operator, because it returns the memory address
SAMPLE CODING #include using namespace std; int main() { int x;//A normal integer int *p;//A pointer to an integer p = &x;//Read it, “assign the address of x to p” cin >> x;//Put a value in x, we could also use *p here cout << *p;//Note the use of the * to get the value }
STRUCTURES Structures are a way of storing many different values in variables of potentially different types under the same name It generally useful whenever a lot of data needs to be grouped together – for instance The format for defining a structure: struct Tag { Members }; Tag is the name of the entire type of srtucture and Members are the variables within the struct
SAMPLE CODING struct database { int id_number; int age; float salary; }; int main() { database employee; employee.age = 22; employee.id_number = 1; employee.salary = 12000; }
End of chapter