Array values reset problem with dynamic allocation - c++

Trying to create a little program using class, dynamic allocation,...
This is the "problematic" code:
void Social::calc_pop(double years) const {
double var = births - deaths;
double* pop = new double;
pop[0] = pop_0;
for (int i = 0; i < years; i++)
{
pop[i+1] = pop[i] + var;
std::cout << "La popolazione all'anno " << i+1 << " è pari a " << pop[i+1] << std::endl;
}
delete pop;
}
The output is (with years = 10, pop_0 = 300, births = 10, deaths = 9):
pop[1] = 301
pop[2] = 302
pop[3] = 303
pop[4] = 304
pop[5] = 1
pop[6] = 1
pop[7] = 1
pop[8] = 2
pop[9] = 3
pop[10] = 4
What's wrong with my code?

This code:
double* pop = new double;
allocates a single double, but then you are treating pop like an array, which invokes undefined behavior when you index into it at any position other than 0.
Instead, you need to allocate an array:
double* pop = new double[years + 1];
Note that you need to make years an int, or cast it to an int inside the new expression.
which is later deleted like this:
delete [] pop;
However, please don't write this code (unless you're just practicing how dynamic allocation works). You can save yourself a lot of trouble by just making pop a vector:
std::vector<double> pop(years + 1);

You're only allocating a single double, which you treat as an array, and that has undefined behaviour if the index is greater than zero.
You also can't allocate an array of years elements, because years is not an integer – what would an array of 3.125 doubles look like?
You don't need any kind of collection for this calculation, only the last known value.
void Social::calc_pop(int years) const {
double var = births - deaths;
double pop = pop_0;
for (int i = 0; i < years; i++)
{
pop = pop + var;
std::cout << "La popolazione all'anno " << i+1 << " è pari a " << pop << std::endl;
}
}

Related

When I try to decompose a double number into an array as elements, why do I get an offset preventing me from getting the last digit?

I have a problem. I want from a given number to get each digit as an element in the same array.
But when I compile, if I extend the range from one iteration above the size of the given number, I get a corrupted data exception from Visual Studio in Debug mode as an exception.
I thought first that was because the int type is only 4 digit max length as a 4 bytes entity because I used to get only one digit for greater number above 9999. But I noticed that my number starts at an iteration value one too late...which makes it impossible to show the last digit.
If I add a zero to my given number, I can manually offset in the opposite direction, but that doesn't work with my original number.
But, I can't find out how to fix that...Here is my code.
Before asking for help, here is a screenshot explaining the principle which is used to convert the number into an array: math theory formula
I wish to solve it with the number type only because the char type involves another way managing the memory with buffers...which I don't really know how to handle right know.
Can someone help me to complete the debugging please ?
#include <iostream>
#include <math.h>
//method to convert user number entry to array of digits
long long numToArray(double num,double arrDigits[], const long long n) {
//instanciate variables
//array of with m elements
arrDigits[n];
double* loopValue = new double(0);
//extract the digits and store them into arrDigits array
for (long long i = 0; i < n; i++) {
long temp = 0;
for (long k = 0; k < i + 1; k++) {
//mathematical general formula
temp += arrDigits[i - k] * pow(10, k);
loopValue = new double(0);
*loopValue = floor(num / pow(10, n - i)) - temp;
arrDigits[i] = *loopValue;
}
std::cout << "digits array value at " << i << " is " << arrDigits[i] << " \n";
}
return 0;
}
//main program interacting with the user
int main()
{
std::cout << "please type an integer: ";
double num;
const long long n = sizeof(num);
double array[n]{};
std::cin >> num;
//call the method to test if all values are in the array
numToArray(num, array, n);
return 0;
}
Explaining the troubleshoot
Note : Visual Studio shows error if I extend from n to n+1. If I let the type int or long, sizeof(num) is all the time 4...
Then, I had to set it as double and to extract it from the main scope, which makes it ...double...
People asking to remove pointer, it is impossible to run the program if I do so.
I want from a given number to get each digit as an element in the same array.
If you want to simply get each number into an array, it takes only a few lines of code to convert the decimal to a string, remove the decimal point (if it exists), and then copy the string to a buffer:
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <algorithm>
#include <iterator>
#include <iomanip>
int main()
{
double d = 1.45624234;
std::ostringstream strm;
strm << std::setprecision(12);
// copy this to a string using the output stream
strm << d;
std::string s = strm.str();
// remove the decimal point
s.erase(std::remove(s.begin(), s.end(), '.'), s.end());
// Now copy each digit to a buffer (in this case, vector)
std::vector<int> v;
std::transform(s.begin(), s.end(), std::back_inserter(v), [&](char ch) { return ch - '0';});
// output the results
for (auto c : v )
std::cout << c;
}
Output:
145624234
All of the work you were doing is already done for you by the standard library. In this case the overloaded operator << for double when streamed to a buffer creates the string. How it does it? That is basically what your code is attempting to do, but obviously safely and correctly.
Then it's just a matter of transforming each digit character into an actual integer that represents that digit, and that is what std::transform does. Each digit character is copied to the vector by subtracting the character 0 from each char digit.
#include <iostream>
#include <math.h>
#include <list>
int main()
{
//Entry request of any natural integer within the range of double type
std::cout << "Please type a natural integer from 1 to 99999999\n";
double num;
std::cin >> num;
//counting the number of digits
int count = 0;
long long CountingNum = static_cast<long long>(num);
while (CountingNum != 0) {
CountingNum = CountingNum/10;
++count;
}
std::cout << "number of digits compositing your natural integer: " << count<<std::endl;
//process the value for conversion to list of digits, so you can
//access each digits by power and enhance your calculus operations
double converternum = num * 10;//removing the right offset to keep the last digit
const int containerSize = sizeof(double); //defining array constant size
int sizeRescale = containerSize - count;//set general offset to handle according to the user entry
double arrDigits[containerSize] = {};//initialize array with a sufficient size.
double* loopValue = new double(0); //define pointer variable to make to operation possible
//extract the digits and store them into arrDigits array
for (long long i = 0; i < containerSize; i++) {
long temp = 0;
for (long k = 0; k < i + 1; k++) {
//mathematical general formula adapted to the computation
temp += arrDigits[i - k] * pow(10, k);
loopValue = new double(0); //reinitialize the pointer
*loopValue = floor(converternum / pow(10, containerSize - i)) - temp; //assign the math formula to the pointer
arrDigits[i] = *loopValue;//assigne the formula for any i to the array relatively to k
}
std::cout << "digits array value at " << i << " is " << arrDigits[i] << " \n";
}
//convert array to a list
std::list<double> listDigits(std::begin(arrDigits), std::end(arrDigits));
//print the converted list
std::cout << "array converted to list: ";
for (double j : listDigits) {
std::cout << j << " ";
}
std::cout << std::endl;
//remove the zeros offset and resize the new converted list
for (int j = 0; j < sizeRescale; j++) {
listDigits.pop_front();
}
std::cout << "removed zero element to the list\n";
for (double i : listDigits) {
std::cout << i << " ";
}
std::cout << "natural integer successfully converted into list digits data\n";
return 0;
}
an example on debug mode in Visual Studio 2019
I finally encapsulated the whole code into two functions. But I have an extra value at first and last iteration...
The answer is almost complete, just need to solve the offset from inside the main moved to it's owned function. I finally added a new array variable with the exact size I want from the two new functions, so we get the array which will be possible to manipulate so far away.
#include <iostream>
#include <math.h>
#include <list>
int CountNumberDigits(int num) {
int count = 0;
long long CountingNum = static_cast<long long>(num);
while (CountingNum != 0) {
CountingNum = CountingNum / 10;
++count;
}
return count;
}
double* NumToArray(double num) {
double converternum = num * 10;//removing the right offset to keep the last digit
const int containerSize = sizeof(double); //defining array constant size
int sizeRescale = containerSize - CountNumberDigits(num);//set general offset to handle according to the user entry
double arrDigits[containerSize] = {};//initialize array with a sufficient size.
double* loopValue = new double(0); //define pointer variable to make to operation possible
//extract the digits and store them into arrDigits array
for (long long i = 0; i < containerSize; i++) {
long temp = 0;
for (long k = 0; k < i + 1; k++) {
//mathematical general formula adapted to the computation
temp += arrDigits[i - k] * pow(10, k);
loopValue = new double(0); //reinitialize the pointer
*loopValue = floor(converternum / pow(10, containerSize - i)) - temp; //assign the math formula to the pointer
arrDigits[i] = *loopValue;//assigne the formula for any i to the array relatively to k
}
}
//convert array to a list
std::list<double> listDigits(std::begin(arrDigits), std::end(arrDigits));
for (double j : listDigits) {
std::cout << j << " ";
}
//remove the zeros offset and resize the new converted list
for (int j = 0; j < sizeRescale; j++) {
listDigits.pop_front();
}
//convert list to array
double* arrOutput = new double[listDigits.size()]{};
std::copy(listDigits.begin(), listDigits.end(), arrOutput);
double* ptrResult = arrOutput;
return ptrResult;
}
int main()
{
//Entry request of any natural integer within the range of double type
std::cout << "Please type a natural integer from 1 to 99999999\n";
double num;
std::cin >> num;
int count = CountNumberDigits(num);
std::cout << "number of digits compositing your natural integer: " << count << std::endl;
double* ptrOutput = NumToArray(num);
//reduce the array to the num size
double* shrinkArray = new double[CountNumberDigits(num)];
for (int i = 0; i < CountNumberDigits(num); i++) {
*(shrinkArray+i) = ptrOutput[i];
std::cout << *(shrinkArray+i) << " ";
}

Intrusive values/addresses when crossing an dynamic allocated 2d array in c++

2D array initialization:
....
int main (...) {
....
double **hes = allocArray (2, 2);
// function (....) returning double
hes[0][0] = function (3, &_X, &_Y, _usrvar_a, _usrvar_b);
hes[0][1] = function (4, &_X, &_Y, _usrvar_a, _usrvar_b);
hes[1][0] = function (4, &_X, &_Y, _usrvar_a, _usrvar_b);
hes[1][1] = function (5, &_X, &_Y, _usrvar_a, _usrvar_b);
....
return 0;
}
double **allocArray (int row, int col) {
double **ptr = new double*[row];
for (int i = 0; i < row; i++)
{
ptr[i] = new double[col];
}
return ptr;
}
Values of 2d double type array is:
12 2
2 14
I know that because I have crossed it with iterators (i, j)
void otherFunc (double **h, ....) {
....
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++)
std::cout << " " << h[i][j];
....
}
Output is
12 2 2 14
(I do not need to separate the rows of 2D array in output, do not write about that)
I want to cross it with pointer:
void otherFunc (double **h, ....) {
....
for (double *ptr = h[0]; ptr <= &h[1][1]; ptr++)
std::cout << " " << *ptr;
....
}
Output is:
12 2 0 1.63042e-322 2 14
Why 0 and 1.63042e-322 appeared here?
h[0] and h[1] in your run are not one just after the other:
h[1] in your specific run happens to be four numbers after h[0].
This behavior probably is random meaning that (as far as we know from your question) probably you didn't explicitly specify the relative positions of h[0] and h[1]. If this is the case the next time you run your code h[1] could even be smaller than h[0] this results in undefined behavior.
What you probably want is something of this kind: allocate four doubles and assign the address of the first to a pointer double* hh = malloc(4 * sizeof(double)); And then for the variable h which is a pointer to pointer double* h[2]; you want to assign the pointers as follows:
h[0] = hh;
h[1] = hh+2;
of course there are safer ways to do this. But this could be a good start.

Variable Length Arrays: How to create a buffer with variable size in C++

I am currently writing a moving average class.
The goal is to be able to specify the buffer size as part of the constructor when a new object of class Running_Average is created.
#include <iostream>
#include "Complex.h"
#include <cmath>
#include<stdio.h>
#include<stdlib.h>
#include <windows.h>
using namespace std;
class Running_Average
{
public:
double sum = 0;
double average = 0;
int i;
double Average(void); // Member functions declaration
void AddSample(double);
Running_Average(int);
};
Running_Average::Running_Average(int size) {
int buffersize = size;
double buffer[buffersize] = { 0 };
}
void Running_Average::AddSample(double val) //Add new values to buffer
{
for (i = 9; i>0; i--)
{
buffer[i] = buffer[i-1];
}
buffer[0] = val;
}
double Running_Average::Average(void) //Calculate Average of current values in buffer
{
for (i = 0; i<buffersize; i++)
{
cout << buffer[i] << endl;
sum += buffer[i];
}
average = sum / buffersize;
sum = 0;
return average;
}
int main()
{
double value;
int i;
int f = 0;
Running_Average test;
for (i = (40); i < (50); i++)
{
test.AddSample(i);
}
while (1)
{
i = rand() % 100;
test.AddSample(i);
value = test.Average();
cout << endl;
cout << value << endl;
cout << endl;
Sleep(1000);
}
}
However, the constructor is giving me grief:
Running_Average::Running_Average(int size) {
int buffersize = size;
double buffer[buffersize] = { 0 };
}
Specifically:
buffer[buffersize]
throws an error in visual studio saying:
expression must have a constant size.
I want the user to specify what buffer size they want to work with when they create a new object by passing their value to the constructor.
How can I make this work without it throwing an error?
Thanks for your help!
EDIT: SOLVED! Thank you everyone for your assistance! I managed to get the function working by using the std::vector to define a variable sized array.
There are plenty of ways to do this. The ones that come to mind from best to worst are :
1 Use std::vector
int buffersize = size;
std::vector<double> buffer(buffersize);
2 Built-in unique pointer or shared pointer (depending on usage)
int buffersize = size;
auto buffer = make_unique<double[]>(buffersize) // C++14
int buffersize = size;
auto buffer = make_shared<double[]>(buffersize) // C++14
3 Allocate manually
int buffersize = size;
double *buffer = new double[buffersize];
// delete [] buffer, must be called later
4 Allocate on the stack (not advised, and platform dependent)
int buffersize = size;
double *buffer = alloca(buffersize * sizeof(*buffer));
Note that in all these cases you could index buffer just like an array.
Standard C++ doesn't have variable length arrays. (Why?) The size of an array must be a constant expression. Some compilers have non-standard extensions that allow VLAs, but you shouldn't rely on them. Use std::vector when you need an array which can have a variable length and can be resized.
Variable length arrays are valid in C but not in C++. In C++ you're better off using a vector collection since that allows you to better represent the intent, a varying array size, without having to maintain the current size separately.
The following complete program gives you a baseline to work from, including test harness code:
#include <iostream>
#include <vector>
class RunningValues {
public:
RunningValues(size_t size = 50);
void Add(double val);
double Sum();
double Average();
private:
std::vector<double> dataBuffer;
size_t sizeLimit;
double sum;
};
// Constructor: store limit and zero sum (vector is already empty).
RunningValues::RunningValues(size_t size): sizeLimit(size), sum(0.0) {}
// Add a sample.
void RunningValues::Add(double val) {
// Zero size, disallow adds.
if (sizeLimit == 0) return;
// If we would exceed limit, remove earliest.
if (dataBuffer.size() == sizeLimit) {
sum -= dataBuffer[0];
dataBuffer.erase(dataBuffer.begin());
}
// Add value to end.
sum += val;
dataBuffer.push_back(val);
}
// Get the average (zero if nothing yet added) or sum.
double RunningValues::Average() {
if (dataBuffer.size() == 0) return 0.0;
return sum / dataBuffer.size();
}
double RunningValues::Sum() {
return sum;
}
// Test harness.
int main() {
RunningValues test(10);
std::cout << "Ave = " << test.Average() << ", sum = " << test.Sum() << '\n';
for (int i = 40; i < 50; ++i)
{
test.Add(i);
std:: cout << "Add " << i << ", ave = " << test.Average() << ", sum=" << test.Sum() << '\n';
}
for (int i = 0; i < 20; ++i)
{
int val = rand() % 100;
test.Add(val);
std:: cout << "Add " << val << ", ave = " << test.Average() << ", sum=" << test.Sum() << '\n';
}
}
A sample run, which shows the averages and sums at various points, is shown below:
Ave = 0, sum = 0
Add 40, ave = 40, sum=40
Add 41, ave = 40.5, sum=81
Add 42, ave = 41, sum=123
Add 43, ave = 41.5, sum=166
Add 44, ave = 42, sum=210
Add 45, ave = 42.5, sum=255
Add 46, ave = 43, sum=301
Add 47, ave = 43.5, sum=348
Add 48, ave = 44, sum=396
Add 49, ave = 44.5, sum=445
Add 83, ave = 48.8, sum=488
Add 86, ave = 53.3, sum=533
Add 77, ave = 56.8, sum=568
Add 15, ave = 54, sum=540
Add 93, ave = 58.9, sum=589
Add 35, ave = 57.9, sum=579
Add 86, ave = 61.9, sum=619
Add 92, ave = 66.4, sum=664
Add 49, ave = 66.5, sum=665
Add 21, ave = 63.7, sum=637
Add 62, ave = 61.6, sum=616
Add 27, ave = 55.7, sum=557
Add 90, ave = 57, sum=570
Add 59, ave = 61.4, sum=614
Add 63, ave = 58.4, sum=584
Add 26, ave = 57.5, sum=575
Add 40, ave = 52.9, sum=529
Add 26, ave = 46.3, sum=463
Add 72, ave = 48.6, sum=486
Add 36, ave = 50.1, sum=501
If you would rather have a solution which avoids vector (it's a bit wasteful to have all that extra functionality when the vector goes from size 0 up to N and then stays there), you can just use a naked array on the heap as a circular buffer.
The code for that is a slight variation (sans main since it hasn't changed):
#include <iostream>
class RunningValues {
public:
RunningValues(size_t size = 50);
~RunningValues();
void Add(double val);
double Sum();
double Average();
private:
size_t count, next, limit;
double sum, *data;
};
RunningValues::RunningValues(size_t size)
: count(0), next(0), limit(size)
, sum(0.0), data(new double[size]) {}
RunningValues::~RunningValues() {
delete[] data;
}
void RunningValues::Add(double val) {
// Zero size, disallow adds.
if (limit == 0) return;
// If we would exceed limit, remove earliest.
if (count == limit) {
sum -= data[next];
--count;
}
// Add value to end.
data[next] = val;
sum += val;
++count;
next = (next + 1) % limit;
}
// Get the average (zero if nothing yet added) or sum.
double RunningValues::Average() {
if (count == 0) return 0.0;
return sum / count;
}
double RunningValues::Sum() {
return sum;
}
The changes from the vector-based solution are fairly minor:
The constructor no longer has a vector (obviously). Instead it has a fixed size array to use as a circular buffer, along with the count and next variables to manage it.
You now need a destructor to clean up the buffer (before, the vector managed itself).
the adding of items now uses count and next (rather than the vector) to figure out how to adjust the sum and keep a tally of the relevant data.
the calculations of average now uses count rather than the vector size.
Other than that, it's actually very similar to the vector-based code above.
Based on the way you use buffer I would suggest using an std::list<double> for it.
Add this to the beginning of Running_Average:
class Running_Average
{
private:
list<double> buffer;
const size_t MaxBufferSize;
public:
...
The constructor :
Running_Average::Running_Average(size_t size)
: MaxBufferSize(size)
{
}
AddSample() and Average() :
void Running_Average::AddSample(double val)
{
if (buffer.size() == MaxBufferSize)
{
buffer.pop_back();
}
buffer.push_front(val);
}
double Running_Average::Average()
{
double sum = 0;
for (auto a : buffer)
{
cout << a << endl;
sum += a;
}
return sum / buffer.size();
}
I would also remove the sum, average and i member variables and instead declare them where they are used (if needed).
expression must have a constant size
double buffer[buffersize] = { 0 };
First, buffersize isn't a constexpr. It is a variable that changes during runtime.
When specifying a size for an array, as per the standard definition of array:
The constant expression specifies the bound of (number of elements in)
the array. If the value of the constant expression is N, the array has
N elements numbered 0 to N-1,
Sample declaration of an array with 5 elements of type double should be like:
double buffer[5]; // 5 is a literal
constexpr int size = 5;
double buffer[size]; // size is constexpr
Second, buffer is a variable-length array (VLA).
VLAs are partly supported in some compilers as an extension.
How can I make this work without it throwing an error?
If you need the length to be variable, use std::vector and initialize it in your constructor:
class Running_Average {
Running_Average(int size): buffer(size, 0) {}
std::vector<double> buffer;
}

C++ - Comparing multiple int arrays and return array with smallest span

I am working on a problem where i have multiple arrays that are to be compared against a single array. The array with the shortest span between indexes will be returned.
Here is an example of a set of arrays i would be working with:
(if it is of any importance these values represent RGB values)
int[] workingset = {55, 34,102};
int[] test1 = {54,36,99};`
int[] test2 = {21,65,231};
int[] test3 = {76,35,1};
int[] test4 = {133,22,3};
Because test1[] values are closest to workingset[], test1[] would be the array that would be returned.
*I apologize for not putting up sample code, but i simply could not think of a way to piece this puzzle together.
you could easily sum up all components (r,g,b) and check which has the smallest difference.
#include <iostream>
int main(int argc, char* args[])
{
int workingset [] = {55, 34,102};
int test1 [] = {54,36,99};
int test2 []= {21,65,231};
int test3 [] = {76,35,1};
int test4 [] = {133,22,3};
int sums [4] = {};
for(int i=0; i<3;++i){
sums[0] += abs(test1[i]-workingset[i]);
}
std::cout << "diff test1 " << sums[0] << std::endl;
for(int i=0; i<3;++i){
sums[1] += abs(test2[i]-workingset[i]);
}
std::cout << "diff test2 " << sums[1] << std::endl;
for(int i=0; i<3;++i){
sums[2] += abs(test3[i]-workingset[i]);
}
std::cout << "diff test3 " << sums[2] << std::endl;
for(int i=0; i<3;++i){
sums[3] += abs(test4[i]-workingset[i]);
}
std::cout << "diff test4 " << sums[3] << std::endl;
int smallestIndex = 0;
int smallestDiff = INT_MAX;
for(int i=0; i< 4; i++){
if(sums[i] < smallestDiff){
smallestIndex = i;
smallestDiff = sums[i];
}
}
std::cout << "array with smallest index: " << smallestIndex << std::endl;
return 0;
}
I edited the microsoft specific includes and datatypes.
What's your metric for "shortest span between indexes"? I'm guessing that you're trying to minimize the sum of the absolute values of the differences between the two arrays?
Once you've defined your metric, try something like this pseudocode:
min_metric = MAX_INT
min_array = null
for array in arrays:
if array.length() == workingset.length():
metric = calculateMetric(workingset, array)
if metric < min_metric:
min_metric = metric
min_array = array
Let me guess too. Assuming you are trying to write a color matcher. Consider these arrays vectors. Then the absolute length of the vector difference between workingset and testX will be the metric to use.
Or in the code:
int [] delta = { 0, 0, 0 };
for (int i = 0; i < delta.length; ++i) delta[i] = workingset[i] - testX[i];
double metric = 0;
for (int x: delta) metric += x * x;
metric = sqrt(metric); // and use this to assess how far away the testX color is from the workingset color (sqrt operation is optional)

Dereferencing object array pointer in C++

I have this small question about dereferencing arrays. I have a method in class like this
T* foo()
{
// create specific array of objects in here
return (array)
}
foo2()
{
myNewArray = *foo();
// exactly the same algorithm as in foo to create checkArray
cout << sizeof(myNewArray) << sizeof(checkArray) << endl;
}
I get two different results, but I expect them to be the same?
Ok, so the additional information about the code:
vec4* getGridAttr()
{
float xval = -0.5;
float yval = -0.75;
float xval2 = -0.5;
float yval2 = -0.75;
vec4 pointsGrid[100];
for (int i=0;i<42;i++)
{
//Draw horizontal lines
if (i % 2 == 0) pointsGrid[i] = vec4(xval, yval, 0.0,1);
else if (i % 2 != 0) {
pointsGrid[i] = vec4((xval+0.75), yval, 0.0,1);
yval += 0.075;
}
}
for (int j=42;j<64;j++)
{
//Draw horizontal lines
if (j % 2 != 0)
{
pointsGrid[j] = vec4(xval2, yval2, 0.0,1);
xval2 += 0.075;
}
else if (j % 2 == 0) {
pointsGrid[j] = vec4(xval2, -yval2, 0.0,1);
}
}
return (pointsGrid);
}
and in my other method, i have this:
void display( void )
{
vec4 points1[100];
//code here populates points1 exactly the same as in getGridAttributes,
cout << "points1 : " << sizeof(points1) << " " << " pointsFromGridAttr : " << sizeof(*getGridAttr()) << endl;
}
The output is points1 : 1600 pointsFromGridAttr 16
Without seeing more code I can't be sure of this, but if you have something like this:
T* arr1 = makeArray();
T arr2[n];
Then arr1 and arr2 would have different sizes. Specifically, arr1 is a pointer, so its size is the size of a pointer, while arr2 is an array, and its size will be the size of a T object times the number of objects in the array.
Although arrays and pointers in C++ can be interchanged in some contexts, they really are different types. T* and T [n] are different types with different sizes. Once an array decays to a pointer, it loses its size information.
Hope this helps!
I guess you would like to compare the length of the arrays. The length of a C array should be calculated as sizeof(array_variable) / sizeof(type_of_array_elements) or sizeof(array_variable) / sizeof(one_element), not just as sizeof(array_variable). For details see this SO question.
Try this:
cout << sizeof(myNewArray) / sizeof(myNewArray[0]) << ", " << sizeof(checkArray) / sizeof(checkArray[0]) << endl;