I seem to be inventing my own syntax here. The idea seemed simple enough: use the keyword 'new' to allocate space for a new integer array, and populate it with a few integers. Where have I gone wrong?

#include <iostream>
using namespace std;

const int SIZE = 5;
int newArrayMaker();

int main () 
{
    int newArray = newArrayMaker();
    cout	<< "The new array has these contents: ";
    for (int i = 0; i < SIZE; i++)
	cout	<< newArray[i]	<< " "; // Error: invalid types int[int] for array subscript

    return 0;
}

// Fn def
int newArrayMaker()
{
	int *intArrayPointer;
	intArrayPointer = new int[SIZE];
	if (intArrayPointer == NULL)
	{
		cout	<< "Error allocating memory\n";
		return 0;
	}
	
	for (int i = 0; i < SIZE; i++)
		*intArrayPointer[i] = 1;
	int newArray = intArrayPointer;
	
	delete [] intArrayPointer;
	intArrayPointer = 0;
	return newArray;
}

Lots of little bits, I'll highlight a few.

#include <iostream>
using namespace std;

const int SIZE = 5;
int* newArrayMaker();

int main () 
{
   int *newArray = newArrayMaker();
   cout << "The new array has these contents: ";
   for ( int i = 0; i < SIZE; i++ )
      cout  << newArray[i] << " ";
   return 0;
}

int* newArrayMaker()
{
   int *intArrayPointer = new int[SIZE];
   for ( int i = 0; i < SIZE; i++ )
   {
      intArrayPointer[i] = 1;
   }
   return intArrayPointer;
}

Edited 6 Years Ago by Dave Sinkula: n/a

Looks like I had the syntax backward! You solved the problem; I can start parsing it and figure out where I went wrong and what the code is really doing. Thanks.

This question has already been answered. Start a new discussion instead.