Hi,
during an assignment I needed to write a function that, among other things, had to print some of an array values. The simplified version that I show below creates an array of 50 pointers, populates it, and prints the values from main and from a function.
I'm really struggling trying to understand three things:

1. Why is there a "0, 0, 17" series between every value of the array when printing from the function?
2. Why a call like "printArray(myArray)" is not compiling (line 31)?
3. Why "cout << *anArray[1]" won't compile when used in the function but compiles when used in main (lines 28 and 42)?

As always I would appreciate any help.

Here is a simplified version of the program.

#include<iostream>
using namespace std;

unsigned long printArray(unsigned long anArray[]);


int main()
{
	unsigned long * myArray[50];  // array of 50 pointers
	unsigned long counterArray=0;
	unsigned long * pTemp;
	
	
	// populate array
	
	for (unsigned long i = 200; i > 150; i--)
	{
		pTemp = new unsigned long;
		*pTemp = i;
		myArray[counterArray] = pTemp;
		counterArray++;
	}
	
	// show the array from main
	
	for (unsigned long i= 0; i< 50; i++)
		{
			cout << i+1 << ": " << *myArray[i] << ";\t";
		}
	
	printArray(myArray[0]); // printArray(myArray) won't compile

	cout << endl;	
	return 0;

}

unsigned long printArray(unsigned long anArray[])
{
	for (unsigned long i= 0; i< 50; i++)
		{
			cout <<  anArray[i] << ";\t"; //  cout << *anArray[1] << "\t"; won't compile
		}
	return 0;
}

Why don't you just do myArray[counterArray] = new unsigned long; in the allocation loop? And don't forget to delete everything too! Considering what you basically want is a 50-element array why don't you do unsigned long *array_50 = new unsigned long[50]; , and then access via the [] operator as per above code. Then you'll only need one delete call: delete []array_50; .

At a guess I'd imagine if you changed the function to: unsigned long printArray(unsigned long *anArray[]) , and call it as follows printArray(myArray); , it should work.

Hi,
thank you twomers.
You are right. Another way it's declaring a pointer to an array of 50 elements on the heap instead of an array of 50 pointers.
I was actually trying to learn how to work with these two methods.

This article has been dead for over six months. Start a new discussion instead.