Returning an array from a function in C++

Kn1ghT

Active Member
Joined
May 13, 2009
Messages
79
Reaction score
0
I want to return an array from a function. I know it is supposed to be simple, using pointers, but I cannot get mine to work right. Only the first value is returning correctly. I think I know why, but I'm not sure how to actually use a pointer to return an array.

Here is the basic idea:

Code:
int main()
{
     #Call function attack()
        int *narray = attack();

	cout << narray[0] << endl;
	cout << narray[1] << endl;
	cout << narray[2] << endl;
}

int * attack()
{
     #Do some calculations
     #Calculate att1, att2, att3
     int Att[] = {att1, att2, att3};
     
     int *Ptr;
     Ptr = &Att[];

     Return Ptr;
}

So I just want to return the values as an array to the main function.

Some thoughts
I think I should declare a global array, then create a pointer in the attack function that points to the global array. Then I initialize the 3 values I want in the global array, in the function. Then return the pointer I declared to function main.

I'm not exactly sure if I am reading the values in the array that is pointed to, correctly like this:

cout << narray[0] << endl;
cout << narray[1] << endl;
cout << narray[2] << endl;

Any tips/ideas?
 
I want to return an array from a function. I know it is supposed to be simple, using pointers, but I cannot get mine to work right. Only the first value is returning correctly. I think I know why, but I'm not sure how to actually use a pointer to return an array.

Here is the basic idea:

Code:
int main()
{
     #Call function attack()
        int *narray = attack();

	cout << narray[0] << endl;
	cout << narray[1] << endl;
	cout << narray[2] << endl;
}

int * attack()
{
     #Do some calculations
     #Calculate att1, att2, att3
     int Att[] = {att1, att2, att3};
     
     int *Ptr;
     Ptr = &Att[];

     Return Ptr;
}

So I just want to return the values as an array to the main function.

Some thoughts
I think I should declare a global array, then create a pointer in the attack function that points to the global array. Then I initialize the 3 values I want in the global array, in the function. Then return the pointer I declared to function main.

I'm not exactly sure if I am reading the values in the array that is pointed to, correctly like this:

cout << narray[0] << endl;
cout << narray[1] << endl;
cout << narray[2] << endl;

Any tips/ideas?

Code:
#include <stdio.h>
#include <stdlib.h>

int* getArray() {
        int* someArray = (int*)malloc(sizeof(int)*2);

        someArray[0] = 1;
        someArray[1] = 2;

        return someArray;
}

int main() {
        int* myArray = getArray();

        printf("%d\n%d\n", myArray[0], myArray[1]);

        return 0;
}
 
Hi Kn1ghT

As a general rule you shouldn't use malloc in C++ (nor arrays, try the STL vector template) especially if you are not freeing the memory afterwards.

However, if you want to use an array you can do the following

Code:
#include <iostream>

void attack(int * const myArray)
{
	for(int i = 0; i < 3; i++)
	{
		myArray[i] = myArray[i]+1;
	}	
}

void main()
{
	int myArray[3] = {1, 2, 3};
	attack(myArray);

	std::cout << myArray[0] << myArray[1] << myArray[2];
}
 
Thanks for the replies. My function is working now.
 
Hi Kn1ghT

As a general rule you shouldn't use malloc in C++ (nor arrays, try the STL vector template) especially if you are not freeing the memory afterwards.

However, if you want to use an array you can do the following

Code:
#include <iostream>

void attack(int * const myArray)
{
	for(int i = 0; i < 3; i++)
	{
		myArray[i] = myArray[i]+1;
	}	
}

void main()
{
	int myArray[3] = {1, 2, 3};
	attack(myArray);

	std::cout << myArray[0] << myArray[1] << myArray[2];
}

why are plain arrays not a good idea and STL templates better?

I always find myself using normal arrays in c++, I just really hate it when i have to use arrays of 2 or 3 dimensions using vectors or lists. I may be a massive noob though :D
 
[-]Where's sn3rd & semaphore, they know this stuff backwards[/-]

Never mind I can't read.
 
Last edited:
Can't resist.... must reply..... :)

As a general rule, in C++ is best practice to follow the 'Caller Allocates/Caller Frees' rule, which says that the calling function always allocate and frees the memory used to store data.

Trust me, after spending a few days hunting down memory leaks you will come to appreciate why this rule is so important. If you have a function returning a pointer to memory, then you're probably breaking the rule.

Rewritten, your code would look something like this,
Code:
int main()
{
     //Call function attack()
        int narray[3] = {0};
        attack(narray, sizeof(narray));

	cout << narray[0] << endl;
	cout << narray[1] << endl;
	cout << narray[2] << endl;
}

void attack(int narray[], size_t arrSize)
{
     //Do some calculations
     //Calculate att1, att2, att3


	if (arrSize>0) narray[0] = att1;
	if (arrSize>1) narray[1] = att2;
	if (arrSize>2) narray[2] = att3;

}
 
What Deenem said is true. Much safer and better to do it that way. Memory leaks can become a nightmare!
 
why are plain arrays not a good idea and STL templates better?

I always find myself using normal arrays in c++, I just really hate it when i have to use arrays of 2 or 3 dimensions using vectors or lists. I may be a massive noob though :D

Plain arrays can be evil, as you can easily corrupt your stack with off-by-one errors

eg.

Code:
int temp2[3] = {1, 2, 3};
temp2[3] = 1;

The error is easy to see here but when it is buried deep inside some code that is causing excel to assert on a traders spreadsheet it is no so fun to find.

Using the STL also makes your code easier to follow IMHO

Code:
#include <iostream>
#include <vector>

std::vector<double> getArray() 
{
	std::vector<double> tempArray;
	
	for(int i = 0; i < 100; i++)
	{
		tempArray.push_back(i);
	}
    
	return tempArray;
}

void main()
{      
	std::vector<double> tempArray = getArray();

	std::cout << tempArray[1] << tempArray[2];
}

There is no const correctness to worry about or memory allocation and deallocation issues and I can easily see from the function signature what I am getting back. I can also create vectors of more advanced data types and objects.
 
Last edited:
Top
Sign up to the MyBroadband newsletter
X