We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
The reason you would use a heap-allocated block of contiguous memory a.k.a. 'array', is because you do NOT know the exact number representing the size of the array at COMPILE TIME.
So basically std::cin >> n; int* A = new int[n]; -> here 'n' will be known at RUNTIME, when the user interacts with the program and enters some number.
BUT! Performing calculations also based on non-const/already known values and using the result as the array size will not work either...
Depending on the compiler, but in GCC using g++, try doing all this with a stack allocated array - it MIGHT let you, and then try it with the -pedantic-errors flag and the compiler WON'T let you do such stuff...
TL;DR
So basically when you DO NOT KNOW the size of an array beforehand (like a hard-coded value '10' for example, or a const int or so) - use heap-allocated arrays!
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Arrays Introduction
You are viewing a single comment's thread. Return to all comments →
The reason you would use a heap-allocated block of contiguous memory a.k.a. 'array', is because you do NOT know the exact number representing the size of the array at COMPILE TIME. So basically
std::cin >> n; int* A = new int[n];
-> here 'n' will be known at RUNTIME, when the user interacts with the program and enters some number. BUT! Performing calculations also based on non-const/already known values and using the result as the array size will not work either... Depending on the compiler, but in GCC using g++, try doing all this with a stack allocated array - it MIGHT let you, and then try it with the-pedantic-errors
flag and the compiler WON'T let you do such stuff...TL;DR So basically when you DO NOT KNOW the size of an array beforehand (like a hard-coded value '10' for example, or a const int or so) - use heap-allocated arrays!