Hi all,
Could anyone help me about returning the array from a function? I believe that it is a syntax error (compile time error) to return an array from a function, but one book mentions briefly that using pointer will solve the issue.
However, my current knowledge does not allow me to see how the pointer can solve this C++ limitation (return a pointer might be dangerous because it might point to the address of local variable, and this variable will go out of scope. Hence, this pointer will point to invalid value). I appreciate for your information.

Recommended Answers

All 16 Replies

However, my current knowledge does not allow me to see how the pointer can solve this C++ limitation (return a pointer might be dangerous because it might point to the address of local variable, and this variable will go out of scope. Hence, this pointer will point to invalid value). I appreciate for your information.

Pass a pointer to the start as a parameter to the function, and then return this pointer when you're done.

#include <iostream>
 
int *foo(int *array)
{
   int *start = array;
   while ( *array )
   {
	  std::cout << *array++ << ' ';
   }
   std::cout << std::endl;
   return start;
}
 
int *bar(int *array)
{
   int *start = array;
   while ( *array )
   {
	  *array++ += 1;
   }
   return start;
}
 
int main()
{
   int myarray[] = {1,2,3,4,5,0};
   foo(bar(foo(bar(foo(myarray)))));
   return 0;
}
 
/* my output
1 2 3 4 5
2 3 4 5 6
3 4 5 6 7
*/

I am sorry. I did not make my point clear. Is there any way to return the array from the function, this array is created within that function? For instance, I want to have one function to return an array like int[] getArray() (it is valid in Java, but not in C++), so is there any pointer trick to create one such function in C++?
Thanks in advance, by the way, thanks Dava

Hi all,
We can see that the result is not what we are expected. Can anyone tell me what need to fix in order to get the correct result using same function? Thanks in advance.

#include <iostream>
#define LENGHT 5


using std::cout;
using std::endl;


int* getArray();
void printArray(int* array);


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


cout << "array in main" << endl;
printArray(array);


return 0;
}


int* getArray()
{
int array[LENGHT] = {1, 2, 3, 4, 5};


cout << "array in getArray()" << endl;
printArray(array);


return array;
}


void printArray(int* array)
{
for (int i = 0; i < LENGHT; i++)
cout << *(array+i) << " ";


cout << endl;
cout << endl;
}


/*
Output
array in getArray()
1 2 3 4 5


array in main
-858993460 -858993460 -858993460 3 1245056


Press any key to continue


*/

One way:

int* getArray()
{
   static int array[LENGHT] = {1, 2, 3, 4, 5};

   cout << "array in getArray()" << endl;
   printArray(array);

   return array;
}

Hi Dave,
I appreciate for your help, but it does not work correctly in the following case. We declare static local variable, so this variable will stay until the program is terminated. Hence, although we want to have 2 different arrays, the first one is modified because 2 pointers in main() actually point in the same memory location. Would you show me another way to do it? By the way, in the first version, I mistyped LENGHT, sorry for that.

#include <iostream>
#define LENGTH 5


using std::cout;
using std::endl;
using std::cin;


int* getArray();
void printArray(int* array);


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


cout << "array in main" << endl;
printArray(array);


int* array2 = getArray();


cout << "array in main" << endl;
printArray(array2);


cout << "array in main" << endl;
printArray(array);


return 0;
}


int* getArray()
{
int static array[LENGTH];


for (int i = 0; i < LENGTH; i++)
{
cout << "Enter an integer: ";
cin  >> array;
}


cout << "array in getArray()" << endl;
printArray(array);


return array;
}


void printArray(int* array)
{
for (int i = 0; i < LENGTH; i++)
cout << *(array+i) << " ";


cout << endl;
cout << endl;
}


/*
Output:


Enter an integer: 1
Enter an integer: 2
Enter an integer: 3
Enter an integer: 4
Enter an integer: 5
array in getArray()
1 2 3 4 5


array in main
1 2 3 4 5


Enter an integer: 10
Enter an integer: 20
Enter an integer: 30
Enter an integer: 40
Enter an integer: 50
array in getArray()
10 20 30 40 50


array in main
10 20 30 40 50


array in main
10 20 30 40 50


Press any key to continue


*/

Hence, although we want to have 2 different arrays, the first one is modified because 2 pointers in main() actually point in the same memory location.

Ah. You want a function that creates a new array each time it is called.

#include <iostream>
 
#define LENGTH 5
 
using std::cout;
using std::endl;
using std::cin;
 
int* getArray();
void printArray(int* array);
 
int main()
{
   int* array = getArray();
   cout << "array in main" << endl;
   printArray(array);
   int* array2 = getArray();
   cout << "array2 in main" << endl;
   printArray(array2);
   cout << "array in main" << endl;
   printArray(array);
   delete[] array2;
   delete[] array;
   return 0;
}
 
int* getArray()
{
   int *array = new int[LENGTH];
   for ( int i = 0; i < LENGTH; i++ )
   {
	 cout << "Enter an integer: ";
	 cin >> array[i];
   }
   cout << "array in getArray()" << endl;
   printArray(array);
   return array;
}
 
void printArray(int* array)
{
   for ( int i = 0; i < LENGTH; i++ )
	 cout << *(array+i) << " ";
   cout << endl;
   cout << endl;
}
 
/* my output
Enter an integer: 1
Enter an integer: 2
Enter an integer: 3
Enter an integer: 4
Enter an integer: 5
array in getArray()
1 2 3 4 5 
array in main
1 2 3 4 5 
Enter an integer: 6
Enter an integer: 7
Enter an integer: 8
Enter an integer: 9
Enter an integer: 10
array in getArray()
6 7 8 9 10 
array2 in main
6 7 8 9 10 
array in main
1 2 3 4 5 
*/

Thanks Dave. However, would you mind if I have another question regarding to the same problem? While I was waiting for your solution, I developed one in below.
I know your code is much superior than mine. I am just confused that why the compiler issues the error when I try to delete the pointers. Could you give me the explanation please?

#include <iostream>
#define LENGTH 5


using std::cout;
using std::cin;
using std::endl;


class Array
{
public:
Array()
{
array = new int(LENGTH);
}


~Array()
{
delete[] array;
}


void setElement(int index, int value)
{
if ( index < 0 || index >= LENGTH )
cout << "INVALID INDEX" << endl;


array[index] = value;
}


int getElement(int index) const
{
if ( index < 0 || index >= LENGTH )
cout << "INVALID INDEX" << endl;


return array[index];
}
private:
int* array;


};


Array* getArray();
void printArray(Array* array);


int main()
{
Array* array = getArray();


cout << "array in main" << endl;
printArray(array);


Array* array2 = getArray();


cout << "array in main" << endl;
printArray(array2);


cout << "array in main" << endl;
printArray(array);


delete array;
delete array2;


return 0;
}


Array* getArray()
{
int value = 0;
Array* array = new Array();


for (int i = 0; i < LENGTH; i++)
{
cout << "Enter an integer: ";
cin  >> value;
array->setElement(i, value);
}


cout << "array in getArray()" << endl;
printArray(array);


return array;
}


void printArray(Array* array)
{
for (int i = 0; i < LENGTH; i++)
cout << array->getElement(i) << " ";


cout << endl;
cout << endl;
}


/*
Output:


Enter an integer: 1
Enter an integer: 2
Enter an integer: 3
Enter an integer: 4
Enter an integer: 5
array in getArray()
1 2 3 4 5


array in main
1 2 3 4 5


Enter an integer: 10
Enter an integer: 20
Enter an integer: 30
Enter an integer: 40
Enter an integer: 50
array in getArray()
10 20 30 40 50


array in main
10 20 30 40 50


array in main
1 2 3 4 5


Press any key to continue
*/

C++ is not my native tongue, but I'll mention a couple of things and try to wade through the linter's output.

First, I believe you are trying to delete the objects twice. Once in main(), and then again in the destructor when the object goes out of scope.

[edit1]

if ( index < 0 || index >= LENGTH )
		 cout << "INVALID INDEX" << endl;
	 array[index] = value;

Here you may attempt to access out of array bounds.
[/edit1]

[edit2]

Array()
{
	 array = new int(LENGTH);
}

I think you want the square brackets.

Array()
{
	 array = new int[LENGTH];
}

[/edit2]

[edit3]
Lint:

[Info 1732] new in constructor for class 'Array' which has no assignment operator
[Info 1733] new in constructor for class 'Array' which has no copy constructor

I forget why, but it's right.
[/edit3]

Hi Dave,
The error is caused because of square bracket[] (I just wrote code in Java, so I used wrong () ). After changing to [], the program runs correctly.
Thanks for everything, Dave.

#include <iostream>
#define LENGTH 5
#define ERROR -1

using std::cout;
using std::cin;
using std::endl;

class Array
{
public:
    Array()
    {
        array = new int[LENGTH];
    }

    ~Array()
    {
        delete[] array;
    }

    void setElement(int index, int value)
    {
        if ( index >= 0 && index < LENGTH )
            array[index] = value;
        else
            cout << "INVALID INDEX" << endl;
    }

    int getElement(int index) const
    {
        if ( index >= 0 && index < LENGTH )
            return array[index];
        else
        {
            cout << "INVALID INDEX" << endl;
            return ERROR;
        }


    }
private:
    int* array;

};

Array* getArray();
void printArray(Array* array);

int main()
{
    Array* array = getArray();

    cout << "array in main" << endl;
    printArray(array);

    Array* array2 = getArray();

    cout << "array in main" << endl;
    printArray(array2);

    cout << "array in main" << endl;
    printArray(array);

    delete array2;
    delete array;

    return 0;
}

Array* getArray()
{
    int value = 0;
    Array* array = new Array();

    for (int i = 0; i < LENGTH; i++)
    {
        cout << "Enter an integer: ";
        cin  >> value;
        array->setElement(i, value);
    }

    cout << "array in getArray()" << endl;
    printArray(array);

    return array;
}

void printArray(Array* array)
{
    for (int i = 0; i < LENGTH; i++)
        cout << array->getElement(i) << " ";

    cout << endl;
    cout << endl;
}

/*
Output: 

Enter an integer: 1
Enter an integer: 2
Enter an integer: 3
Enter an integer: 4
Enter an integer: 5
array in getArray()
1 2 3 4 5

array in main
1 2 3 4 5

Enter an integer: 10
Enter an integer: 20
Enter an integer: 30
Enter an integer: 40
Enter an integer: 50
array in getArray()
10 20 30 40 50

array in main
10 20 30 40 50

array in main
1 2 3 4 5

Press any key to continue
*/
#include <iostream>
#include <cstring>
#include <string>

using namespace std;

string plainfirst;
string key;

char*  perkey(char astr[]){ // permutate key
// cout<<"deneme "<<astr;
char* ptr;
 for(int i = 0; i<strlen(astr); i++){
   *(ptr + i) = astr[i];
   *(ptr + i) = '\0';
}

return ptr;
}

void printArray(char* array)
{

    for (int i = 0; i <10; i++){
        cout << *(array+i) << " ";
    }
    cout << endl;
    cout << endl;
}

int main (){

char str[10];

cout<<"key: ";
cin.getline(str,10,'$');

char* e = perkey(str);



printArray(e);

return 0;
}

i couldn't returned array is writen, how can i solve this problem.

Why are you hijacking a 3 year old thread? Can't you start a new thread with your new problem?

Why are you hijacking a 3 year old thread? Can't you start a new thread with your new problem?

Gosh! when did Jack Nichalson change his name and become a C
programmer?!!

function perkey() is using an unitilized pointer ptr Is the intent of that function to copy the contents of one string into another and return the pointer to the new string? Like strcpy() ? If so, then you need to call malloc() first to allocate memory for the new string.

printArray -- why are you using a loop to print each individual character when cout will print the entire string in one shot ?

And yes, you should have just started a new thread to ask your question.

[edit]Ok , ok so I failed to look at the datestamp of egemen's post -- three months old :-O [/edit]

Gosh! when did Jack Nichalson change his name and become a C
programmer?!!

And what makes you think Nichalson doesn't know how to program in C ?

> Ok , ok so I failed to look at the datestamp of egemen's post -- three months old
Yeah, a 3 month bump, which in itself began as a bump of a 3 YEAR old thread.

I bet Jack knows how to spell his own name, regardless.

#include <topic.h>
Error - topic not found - entering thread wibble mode.

Can we close this now?

Can we close this now?

I don't think that's necessary -- it will probably die on its own. And DaniWeb rules don't permit closing a thread just because someone bumped it.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.