My task was to write a function that dynamically allocates an array of integers. The function should accept an integer argument indicating the number of elements to allocate. The function should return a pointer to the array.

Here is the code I wrote, my pointer returns the starting address of the array but im having trouble getting it to display all the integers. The error says cannot convert int = int* what did I do wrong?

//jc test

#include <iostream>
using namespace std;

int getElements(int); //Function protoype.

int main()
	int *elements; //To point to elements.

	//Get array of the 5 entered numbers.
	elements = getElements(5);

	//Display numbers.
	for (int set = 0; set < 5; set++)
		cout << elements[set] << endl;

	return 0;


int getElements(int num)
	const int SIZE = 5; //To hold 5 numbers.
	int numbers[SIZE]; //To hold numbers.
	int count; //Counter.
	int *ptr; //To point to numbers.

	ptr = new int[SIZE]; //Dynamically Allocated Array.

	//Enter 5 numbers.
	cout << "Enter " << SIZE << " numbers: ";
	for (count = 0; count < SIZE; count++)
		cin >> numbers[count];
		ptr = &numbers[0];

	return *ptr;

Edited by JCal1108: forgot to use code tag, sorry.

6 Years
Discussion Span
Last Post by Unimportant
int* getElements(int num) { // don't return "int" unless you cast to pointer later
  int *ptr; // this is a pointer to int
  ptr = new int[num]; // it is still a pointer to int, since the new array is of ints
  //Enter 5 numbers.
  std::cout << "Enter " << num << " numbers: ";
  for (int i=0;i<num;++i) {
    std::cin >> ptr[i]; // now we fill the array with ints
  return *ptr; // and this pointer can be used as the array, which has no
               // real name of its own, just a place in heap memory
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.