Jan 2, 2015 at 11:53am Jan 2, 2015 at 11:53am UTC
Hello,
I decided to move on with the exercises, here was my task:
1. Allocate an array of ten ints on the free store using new.
2. Print the values of the ten ints into cout.
3. Deallocate the array using delete[]
Output:
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
Does this seem like right result?
Jan 2, 2015 at 3:52pm Jan 2, 2015 at 3:52pm UTC
You don't indicate if you explicitly initialized the array to zeroes.
new
does not initialize the returned memory.
If you want a better answer, post your code.
Jan 2, 2015 at 6:35pm Jan 2, 2015 at 6:35pm UTC
int * a = new int [10] {100,101,102,103,104,105,106,107,108,109,110};
You are trying to put 11 ints into an Array of 10.
if they are by default 0.
They are (should not be) by default zero. Thye are some garbage values.
ost << a[n] << ", " ;
You called it 'os', remember? Do you even read your compiler errors? Are you trolling me?
Try this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
#include <iostream>
void print_array(std::ostream& os, int * arr, std::size_t sz)
{
os << '{' ;
for (std::size_t i = 0; i < sz; ++i) {
os << arr[i];
if (i != sz-1) os << ", " ;
}
os << '}' ;
}
int main()
{
const std::size_t amount = 10;
int *numbers = new int [amount];
for (std::size_t i = 0; i < amount; ++i)
numbers[i] = 100 + i;
print_array(std::cout, numbers, amount);
delete [] numbers;
}
I highly recommend not using naked new/delete and using std::array instead of C-Style arrays.
I made the print_int_array(aka print_array()) function take a variable size, so it isn't completely useless.
Last edited on Jan 2, 2015 at 6:37pm Jan 2, 2015 at 6:37pm UTC