Array of ten ints

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?
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.
Well, I moved on so here is the two other questions:

5. Write a function print_array10(ostream& os, int*a) that prints out the values of a (assumed to have ten elements) to os.

6. Allocate an array of ten ints on the free store; initialize it with the values 100,101,102, etc.; and print out its values.


code so far:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40


#include <iostream>
#include <new>
using namespace std;

print_array10(ostream& os, int* a)

{

   for (int n=0; n<10; n++)
  {
  
   ost << a[n] << ", ";

  }


}


int main ()
{



   int* a = new int[10] {100,101,102,103,104,105,106,107,108,109,110};

  
   print_array10();  


   delete[] a;

   return 0;


}





I don`t really know how to use ostream.

Still, elements should now be initialized to some value if they are by default 0.
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
Topic archived. No new replies allowed.