I'm having trouble understand what the benefits of using pointers actually are.
I understand that they're ment to be quite a powerful feature in C++ but I don't quite understand what are so good about them, if someone could explain it would be appreciated
Pointers are the foundation of the STL's containers and iterators. Without them, the majority of the STL will collapse.
The most common uses for pointers are dynamic memory allocation (the pointer points to the allocated memory) and iteration. Unless you dig deep into code, you'll never appreciate them. It's safe to say that pointers, when used correctly, can produce effective and efficient code.
On a side note, there's different types of pointers:
- Basic pointer
- Pointer to members (the tutorial on this site seem to lack information regarding these)
- Pointer to arrays
- Pointer to functions
//******************************************************************************
//POINTER, DYNAMIC DATA, REFERENCE TYPE
//******************************************************************************
////////////////////////////////////////////////////////////////////////////////
//POINTER
////////////////////////////////////////////////////////////////////////////////
/*Declaration of pointer*/
int* pointer;
/*Point to*/
int beta;
pointer = &beta //& = address of
/*Assign value*/
*pointer = 30 //This will make beta = 30
/*Pointing to a structure*/
struct People
{
int age;
string name;
}
People Thang;
//Declare and point PeoplePointer to Thang
People* PeoplePointer = &Thang;
/*Accessing data within structure*/
PeoplePointer->age = 20; //Thang.age = 20
(*PeoplePointer).age = 20; //Thang.age = 20
/*Declare an array of pointer*/
People* PeopleArr[20];
//access
PeopleArr[2]->age = 20; //Assign age = 20 to the third People in the array
/*Pointer Expression*/
int arr[100];
int* pointer;
//The assignment statement
pointer = arr;
//has exactly the same effect as
pointer = &arr[0];
//both store the base adress of arr into pointer
/*
*The expression pointer++ causes
*pointer to point to the next element of the array
*/
pointer = &arr[0];
pointer++; //pointer = &arr[1];
////////////////////////////////////////////////////////////////////////////////
//DYNAMIC DATA
////////////////////////////////////////////////////////////////////////////////
/*The use of new and delete*/
int* pointer;
char* namePointer;
pointer = newint; //Creats a variable of type int and store its address into pointer
namePointer = newchar[6]; //Creats a 6 element array and store its base address into namePointer
delete pointer; //pointer now points at nothing. pointer is undefined
delete [] namePointer; //namepointer is now undefined
/*Prevent memory leak*/
int* ptr1 = newint;
int* ptr2 = newint;
*ptr2 = 44; //assign 44 to "value pointed by ptr2"
*ptr1 = *ptr2; //*ptr = 44
delete ptr1; //delete ptr1
ptr1 = ptr2; //make ptr1 point to same address as ptr2
delete ptr2; //delete ptr2
ptr1 = NULL; //prevent dangling pointer
cin.get();
return 0;