heap memory

why isn't this valid - int number = new int[20] while I can allocate heap(free store) memory to a pointer? int *number = new[int];


1
2
3
4
5
  int main()
{

   int number = new int[20]; // why is this not valid?
}


and when I print out the address of the a pointer in the heap the value is not in hexadecimal format its in numerical format why is this?

1
2
3
4
5
6
7
8


int main()
{

   int *number = new int[20];
   cout << number[0];
}


Last edited on
closed account (E0p9LyTq)
adam2016 wrote:
int number = new int[20]; // why is this not valid?

You are trying to assign a pointer, a pointer to a block of heap memory, to an integer.

1
2
3
4
5
int main()
{
   int *number = new int[20];
   cout << number[0];
}

Where are you initializing the array? When you output the value of the first element you are displaying a garbage value.

int *number = new int[20] {}; initializes the array for all elements to contain 0 (zero).

You can also use "pointer math" (an advanced subject) to access the array elements:
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>

int main()
{
   int* number = new int[5] {5, 10, 15, 20, 25};

   for (int i = 0; i < 5; i++)
   {
      std::cout << *number << "  ";
      number++;
   }
   std::cout << "\n";
}
Last edited on
Topic archived. No new replies allowed.