Pointer - Introducing pointers
A simple pointer program:
#include <iostream>
int main()
{
int num = 3;
//Creat a pointer variable to an int type
// In other words, it will contain the memory address of an int data type
//int *pNum;
//Assign the address of num to pNum so that it points to the num variable in memory
//the & symbol, in this instance, is known as the address-of operator and it allows us
//to get at the memory address for the num variable.
//pNum = #
//NOTE: A word of caution when using pointers. You should always initialize a pointer variable
//to NULL, nullptr, 0, or with a memory address. Leaving a pointer variable uninitialized is
//an error that can result in difficult to find bugs and create security issues for your code.
// int *pNum; // not recommended
int *pNum = #
//NOTE2: when declaring a pointer, ensure that the variable you will be pointing to is the same
//data type as the pointer you are declaring. This is important because of the difference in the
//number of bytes stored in the various data types.
//Print to screen
std::cout << num <<std::endl;
std::cout <<&num<< std::endl;
std::cout <<pNum<<std::endl;
return 0;
}
Last updated