C++ Pointer Note

Johnny Chen
1 min readJul 3, 2022

--

  1. Pointer Introduction
#include <iostream>
using namespace std;
int main(){
int n = 5;
cout << &n << endl; // print the memory location of int n
int* ptr = &n; // create a pointer ptr points to n variable
cout << ptr << endl; // memory location
cout << *ptr <<endl; // 5
system("pause>0");
}

2. Change array size at runtime

Since array need to declare the size, ie myArray[3] = {5, 4} , it is not allowed to change the size of the array. (Like the following example)

int main(){
int size;
cout << "Input the size of the array: " << endl;
cin >> size;
int myArray[size]
}

However, we can use “dynamic array” to change the size of the array at runtime:

int main(){
int size;
cout << "Input the size of the array: "<< endl;
cin >> size;
int* myArray = new int[size];

// print out the array
for (int i = 0; i < size; i++){
cout << "Array[" << i << "]: ";
cin >> myArray[i];
}
for (int i = 0; i < size; i++){
cout << myArray[i] << " ";
}
delete[] myArray;
myArray = NULL;

system("pause>0");
}

Two things to be noted:

  1. Use int* array_name = new int[size]; to create a dynamic array.
  2. Once create the dynamic array, remember to delete using command delete[] array_name

--

--