C++ Pointer Note

#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. Once create the dynamic array, remember to delete using command delete[] array_name

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store