how do pointers work in c++ code example
Example 1: what is this pointer in c++
Every object in C++ has access to its own address through an important pointer called this pointer.
The this pointer is an implicit parameter to all member functions.
Therefore, inside a member function,
this may be used to refer to the invoking object.
Friend functions do not have a this pointer,
because friends are not members of a class.
Only member functions have a this pointer.
Example 2: pointers in cpp
#include <iostream>
using std::cout;
int main() {
/*
Some things to keep in mind:
-you shouldn't circumvent the type system if you are creating raw ptrs
and don't need to "type pun" or cast (don't use void ptrs)
-ptr types only reference memory (which are integers), not actual data, thus
they should not be treated as data types
char* is just 1 byte of mem, int* is just 4 bytes of mem, etc
- '*' means that you are creating a pointer which "points" to the mem address
of a variable
- '&', in this case, means "get the mem address of this variable"
*/
void* ptr; // a pointer that doesn't reference a certain size of memory
int* int_ptr; // a pointer that points to data with
// only 4 bytes of memory (on stack)
int a = 5; // allocates 4 bytes of mem and stores "5" there (as a primitive)
ptr = &a; // can only access the memory address of 'a' (not the data there)
int b = 45;
int_ptr = &b; // can access both memory address and data of 'b'
cout << ptr << "\n"; // prints mem address of 'a'
/*cout << *ptr << "\n"; <- this will error out; a void ptr cannot be
derefrenced */
cout << *(int*)ptr << "\n"; // type punning to get around void ptr (extra work)
cout << int_ptr << "\n"; // mem address of b
cout << *int_ptr << "\n"; // data stored at b
/* -- OUTPUTS -- */
/*
some memory address (arbitrary) which contains 05 00 00 00 as its data
5
some memory address (arbitrary) which contains 2D 00 00 00 as its data
45
*/
return 0; // you only need this if "main" isnt the linker entry point
// you also don't care
// ur also probably wondering why I didn't using namespace std... cherno
}
Example 3: c++ pointers
// my first pointer
#include <iostream>
using namespace std;
int main ()
{
int firstvalue, secondvalue;
int * mypointer; //creates pointer variable of type int
mypointer = &firstvalue;
*mypointer = 10;
mypointer = &secondvalue;
*mypointer = 20;
cout << "firstvalue is " << firstvalue << '\n'; //firstvalue is 10
cout << "secondvalue is " << secondvalue << '\n'; //secondvalue is 20
return 0;
}
Example 4: pointer in c++
int* pointVar, var;
var = 5;
// assign address of var to pointVar
pointVar = &var;
// access value pointed by pointVar
cout << *pointVar << endl; // Output: 5
In the above code, the address of var is assigned to the pointVar pointer.
We have used the *pointVar to get the value stored in that address.