Returning a dynamically created array from function - c++

I'm trying to create a function that would dynamically allocate an array, sets the values of the elements, and returns the size of the array. The array variable is a pointer that is declared outside the function and passed as a parameter. Here is the code:
#include <cstdlib>
#include <iostream>
using namespace std;
int doArray(int *arr) {
int sz = 10;
arr = (int*) malloc(sizeof(int) * sz);
for (int i=0; i<sz; i++) {
arr[i] = i * 5;
}
return sz;
}
int main(int argc, char *argv[]) {
int *arr = NULL;
int size = doArray(arr);
for (int i=0; i<size; i++) {
cout << arr[i] << endl;
}
return 0;
}
For some reason, the program terminates on the first iteration of the for loop in main()! Am I doing something wrong?

If you want to allocate memory that way you have to use:
int doArray(int*& arr)
else the pointer will only be changed inside the function scope.

You're passing in the array pointer by value; this means that when your doArray function returns, the value in arr in main is still NULL - the assignment inside doArray doesn't change it.
If you want to change the value of arr (which is an int *), you need to pass in either a pointer or a reference to it; hence, your function signature will contain either (int *&arr) or (int **arr). If you pass it in as a ** you'll also have to change the syntax inside the function from using arr to *arr (pointer-dereferencing), and you'll call it like so: doArray(&arr).
Also, in C++ you should really be using new int[sz] instead of malloc.

You need to add an extra level of indirection to doArray. As written it allocates the array properly but it doesn't communicate the pointer value back to the caller correctly. The pointer from malloc is lost once you return.
If you wrote a function to take a float and change the value, passing the changed value back to the caller, it would need to take a pointer: foo(float *f). Similarly, here you want to pass back an int* value to the caller so your function must be declared as doArray(int **arr) with a second asterisk.
int doArray(int **arr) {
int sz = 10;
*arr = (int*) malloc(sizeof(int) * sz);
for (int i=0; i<sz; i++) {
(*arr)[i] = i * 5;
}
return sz;
}
int main(int argc, char *argv[]) {
int *arr = NULL;
int size = doArray(&arr);
for (int i=0; i<size; i++) {
cout << arr[i] << endl;
}
return 0;
}
Notice how it now dereferences *arr inside of doArray, and how the call is now written as doArray(&arr).

The arr variable in your function is a local copy of the arr pointer in the main function, and the original is not updated. You need to pass a pointer-to-pointer or pointer reference (the former will also work in plain c, the later only in c++).
int doArray(int **arr)
or
int doArray(int*& arr)

Change signature to (specific for c++):
int doArray(int *&arr)
so pointer would be changed at exit from doArray.

You need a pointer to a pointer in your doArray() parameter. If you've never done any programming with pointers before, this can be confusing. I find that it can be easier to see the right types if you annotate your code abundantly with typedefs.
You have the right idea that (int*) can be used to represent an array. But if you want to change the value of your variable arr in main(), you need a pointer to that, and so you will end up with (untested code) something like the following
typedef int *IntArray;
int doArray(IntArray *arr) {
int sz = 10;
*arr = (IntArray) malloc(sizeof(int) * sz);
IntArray theArray = *arr;
for (int i=0; i<sz; i++) {
theArray[i] = i * 5;
}
return sz;
}
when calling doArray, you will need to pass the address of your variable (so doArray knows where to write to):
int main(int argc, char *argv[]) {
int *arr = NULL;
int size = doArray(&arr);
for (int i=0; i<size; i++) {
cout << arr[i] << endl;
}
return 0;
}
This should work.

As others have pointed out, you're passing your array (the int *) by value, so when you say arr=... you're not actually changing the array you passed in.
You're also got a memory leak, as you've written it. It's not a big deal when you only call doArray once in the body of your program, but if it gets called repeatedly and the array is never freed (or deleted, if you made it with new) then it can cause problems. Typically the best way to deal with this is by using the STL. You'd then write
#include <vector>
#include <iostream>
int doArray(std::vector<int> &arr) {
int sz = 10;
arr.resize(sz);
for (int i=0; i<sz; i++) {
arr[i] = i * 5;
}
return sz;
}
int main(int argc, char *argv[]) {
std::vector<int> arr;
int size = doArray(arr);
for (int i=0; i<size; i++) {
std::cout << arr[i] << std::endl;
}
return 0;
}
However, with the STL there are more idomatic ways than returning the size, since you can just ask for arr.size(), and if you get really fancy, can use functions like for_each or the ostream_iterator to print all your elements.

Related

Printing array obtained as a return value C++ [duplicate]

This question already has answers here:
Closed 10 years ago.
The following code is printing garbage values. I am passing an array to a function which adds 5 to every element, but when it returns that array's pointer, the main is showing garbage.
I have tried both indexing and pointers there in main but still same results. How can I fix this?
# include <conio.h>
# include <iostream>
using namespace std;
int * add5ToEveryElement(int arr[], int size)
{
int theArray[5];
for(int i=0; i<size; i++)
{
theArray[i] = arr[i] + 5;
cout<<theArray[i]<<endl;
}
return theArray;
}
void main()
{
const int size = 5;
int noArr[size];
for(int i=0; i<size; i++)
{
noArr[i] = i;
}
int *arr = add5ToEveryElement(noArr, size);
cout<<endl;cout<<endl;
for(int i=0; i<size; i++)
{
cout<<arr[i]<<endl;
}
cout<<endl;cout<<endl;cout<<endl;cout<<endl;
for(int i=0; i<size; i++)
{
cout<<*arr<<endl;
*arr++;
}
getch();
}
theArray is a local array in the function add5ToEveryElement() which you are returning to main(). This is undefined behaviour.
Minimally you can change this line:
int theArray[5];
to:
int *theArray = new int[5];
It'll work fine. Don't forget to delete it later in main(). SInce you modify the original pointer, save it:
int *arr = add5ToEveryElement(noArr, size);
int *org = arr;
// Rest of the code
//Finally
delete[] org;
Returning an array from a function is generally considered bad.
Unless you MUST have a "new" array, I would suggest the typical case in C and C++ is to modify the input array. If the CALLING function wants to have two separate arrays, then it can do so by making it's own copy. Alternatively, you could write your code to have two arrays passed into your function, e.g.
void add5ToEveryElement(int arr[], int arr2[], int size)
{
for(int i=0; i<size; i++)
{
arr2[i] = arr[i] + 5;
cout<<theArray[i]<<endl;
}
}
then your main would call with two array arguments, and if you wish to use the same as input and output it will do that too.
Sure, this isn't exactly the answer to your question, but it gives a "better" solution to your problem.
I generally dislike allocation in functions - especially "hidden" allocation (this function says it's adding 5 to every element, not "allocate array with added 5 to each element". Code should never do surprising things, and allocating memory is a little bit of a surprise if you only asked for adding 5 to each element)
this is the perfect code
# include <conio.h>
# include <iostream>
using namespace std;
int * add5ToEveryElement(int arr[], int size)
{
int *theArray = new int[5];
for(int i=0; i<size; i++)
{
theArray[i] = arr[i] + 5;
cout<<theArray[i]<<endl;
}
return theArray;
}
void main()
{
const int size = 5;
int noArr[size];
for(int i=0; i<size; i++)
{
noArr[i] = i;
}
int *arr = add5ToEveryElement(noArr, size);
int *p = arr;
cout<<endl;cout<<endl;
for(int i=0; i<size; i++)
{
cout<<arr[i]<<endl;
}
cout<<endl;cout<<endl;cout<<endl;cout<<endl;
for(int i=0; i<size; i++)
{
cout<<*arr<<endl;
*arr++;
}
getch();
delete[] p;
}

How to add elements to a pointer array?

I'm trying to understand pointers in C++ by writing some examples. I tried creating a pointer array and when I was trying to add integers to it does not work properly. I want to add integers from 0 to 9 to pointer array and print it.
int *array;
array = new int[10];
for(int i=0; i<10; i++){
*array[i] = i;
cout<<*array<<endl;
}
The following will do what you've described:
#include <iostream>
int main()
{
int* array = new int[10];
for (int i = 0; i < 10; ++i)
{
array[i] = i;
std::cout << array[i] << std::endl;
}
delete [] array;
return 0;
}
However in modern C++ the idomatic solution would be something like this:
#include <iostream>
#include <vector>
int main()
{
std::vector<int> v;
for (int i = 0; i < 10; ++i)
{
v.push_back(i);
std::cout << v[i] << std::endl;
}
return 0;
}
You allocated memory for 10 integers for pInt but do not allocate any memory for array. Since array doesn't have any memory allocated it can not hold data. One solution is to just use your pInt variable. On that note where you have *array[i] = i; there is no need to dereference with * as having the brackets [] dereference the pointer. So you can replace that line with pInt[i] = i; then if you call cout << *pInt; you would get the first value in the array. You can cout each in a for loop like cout << pInt[i]; One final thing that you may already know but just incase, whenever you use pointers and allocate memory by using new make sure you deallocate that memory when you are done to prevent memory leaks. For this you would do delete[] pInt;
Allocate something in array otherwise how do you expect it to hold something.(unless you point it to some already allocated memory).
Or assign array=pInt and then you can use it to hold values. array[i]=i
An example:
#include <iostream>
using namespace std;
int main()
{
int *a;
// int *b;
// b= new int[10]; we can simply allocate it to 'a' directly
// a = b;
a = new int[10];
for(int i=0;i<5;i++)
a[i]=i;
for(int i=0;i<5;i++)
cout<<a[i];
delete[] a;
return 0;
}
The pointer variable is nothing but address holder. So here a is not
holding anything significant before initializing. But once you
initialize it either by allocating new or assign it to something
similar it just doesn't point to nowhere. And once you do that you
have some chunk of memory which you can access by that pointer which
is what i did here. What if I didn't initialize and tried to use a.
it's Undefined behavior.
Don't use bits/stdc++.h Link. It might help you write small code but it should never be used in development or production level code.
You should declare a variable as
int *array=new int;
try this
int *array=new int;
int *pInt = new int[10];
for(int i=0; i<10; i++){
*array = i;
cout<<*array<<endl;
}
and if you want to display array from 0 to 9
try this
int *array=new int[10];
int *pInt = new int[10];
for(int i=0; i<10; i++){
array[i] = i;
cout<<array[i]<<endl;
}
for Adding of array
try this
int *array=new int;
int *pInt = new int[10];
for(int i=0; i<10; i++){
pInt[i]=i;
cout<<pInt[i]<<endl;
*array=*array+pInt[i];
}
cout<<"Addition ="<<*array;
return 0;

Reverse Pointer function issue

I'm having an issue with the pointer return function. The error, "calling object type 'int* ' is not a function or a function pointer" reverseArray = reverseArray(array,size);.I am not sure why it's giving me this error, this is not my solution I'm using this solution as a guidance to help me solve the problem. Since I've sat for now 2 hours trying to solve it and I got no where with it, so I decide to look it up and get an idea on how to approach the problem. And break down their solution by using a debugger to see why their solution works. I know it's a bad thing to do because I'm not learning how to solve problems on my own.
#include <iostream>
int* reverseArray(int [], int );
int main()
{ const int size =5;
int array[size] = {1,2,3,4,5};
int* reverseArray;
for(int i =0; i < size;i++)
{
std::cout << array[i];
}
reverseArray = reverseArray(array,size);
for(int i =0; i <size;i++)
{
std::cout <<array[i];
}
return 0;
}
int* reverseArray(int array [],int size)
{
int* newArray;
newArray = new int[size];
int j = 0;
for(int k =size-1;k>=0;k--)
{
newArray[j] = array[k];
j++;
}
return newArray;
}
The error is self explanatory.
"calling object type 'int* ' is not a function or a function pointer". In you main() function, you named the array you want to pass as a parameter to your reverseArray() function with the same name as your function (reverseArray). The compiler get confused within that scope, because of this and thinks you're calling a variable as a function.
See below:
#include <iostream>
int* reverseArray(int [], int );
int main()
{ const int size =5;
int array[size] = {1,2,3,4,5};
int* reverseArray; // Change this name to something else
for(int i =0; i < size;i++)
{
std::cout << array[i];
}
reverseArray = reverseArray(array,size);
for(int i =0; i <size;i++)
{
std::cout <<array[i];
}
return 0;
}
Hope it helps :)

Return an array of compared char pointers in C++ [duplicate]

This question already has answers here:
Can a local variable's memory be accessed outside its scope?
(20 answers)
Closed 8 years ago.
I'm at college and we're learning pointers. Our job was to input a char, compare it to an array and return a pointer to the first reference of that char in the array. But, as I don't like easy things, I've asked my teacher what about having that char more than once in the array.
That's where my headache begins.
So I have this code. The idea is: create a function that compares the input char to the entire array, get the pointers of the references and save them in an array and return that array.
Unfortunately it's not working as I wish :(
What can be wrong?
#include<iostream>
#include<cstdlib>
using namespace std;
char list [10];
int main()
{
initialize();
show();
cout<<search('1');
}
void initialize()
{
int i;
for(i=0; i<10;i++)
{
list[i]='1';
}
}
void show()
{
int i;
for(i=0; i<10;i++)
{
cout<<list[i];
}
}
int* search(char* input)
{
int* result[10];
int i;
char *temp;
for (i=0; i<10; i++)
{
*temp=list[i];
if(strcmp(temp, input) != NULL)
{
result[i]=i;
}
}
return result[];
}
I'm on a mobile device so I can't go into huge detail unfortunately, but you are returning a pointer to an array that you create in the function which goes out of scope at the end of the function.
My massive edit:
As everyone has already stated, a C++ array is actually only a pointer to the first element in the array. As a result, if you return a pointer to an array created in the scope of the function, you are returning a pointer to garbage. If I were doing this I would use a vector, but if I were to be forced into using an array, I would use something like the code below. Hope this helps!
#include <iostream>
#include <cstdlib>
void initialize(char* list) {
for(int i = 0; i < 10; ++i) {
if(i < 4) {
list[i] = '2';
} else {
list[i] = '1';
}
}
}
void show(char *list) {
for(int i = 0; i < 10; ++i) {
std::cout << list[i] << ' ';
}
std::cout << std::endl;
}
// Note the function requires an additional argument that is a pointer
// this is how you can avoid returning a pointer
int search(char input, char* list, char* result) {
int j = 0;
for(int i = 0; i < 10; ++i) {
// comparing characters can be done via ==
if(input == list[i]) {
*(result + j) = list[i];
// You could use result[j], but I used this to show that
// result really is just a pointer to the first element
// of the array. As a result saying result[j] is the same
// as saying I want to deference j elements past the first
// element or *(result + j)
++j; // increment j
}
}
// return how many elements matched
return(j);
}
int main(int argc, char *argv[]) {
char list[10];
char temp[10];
initialize(list);
show(list);
int size = search('1', list, temp);
// create a dynamically sized array containing space for each match
// because we don't know the size at compile time we must use
// a library type or a dynamically sized array
char *result = new char[size];
for(int i = 0; i < size; ++i) {
result[i] = temp[i];
// again you could use result[i]
std::cout << *(result + i) << std::endl;
}
delete[] result; // otherwise you'll get a memory leak
return(0);
}

Why does an array of pointers initializes itself when function finishes?

My weekend assignment was to make a function that gets an array of integers and the size of the array, and creates an array of pointers so that the pointers will be sorted using bubble sort (without changing the original array).
While debugging I found out that it works just fine, but when the function goes back to main() the pointers array gets initialized and everything's gone.
#include <iostream>
using namespace std;
void pointerSort(int arr[], int size, int* pointers[]);
void swap(int a, int b);
void main()
{
int arr[5]={7,2,5,9,4};
int size = 5;
int* pointers[5];
pointerSort(arr, size, pointers);
for (int i = 0; i < 5 ; i++)
cout << *pointers[i] << endl;
}
void pointerSort(int arr[], int size, int* pointers[])
{
int j, i;
bool change = true;
pointers = new int*[size];
for (i = 0; i < size; i++)
pointers[i] = &arr[i];
i = 0;
j = 1;
while (i <= size-1 && change == true)
{
change = false;
for (i = 0; i < size-j; i++)
{
if (*pointers[i] > *pointers[i+1])
{
swap(pointers[i], pointers[i+1]);
change = true;
}
}
j++;
}
}
void swap(int&a, int&b)
{
int temp;
temp = a;
a = b;
b = temp;
}
pointers = new int*[size];
At this point pointers is already an array of pointers, no allocation is needed.
After this line pointers IS NO LONGER THE ARRAY IN YOUR MAIN FUNCTION.
This is why your function is failing, because you are reassigning the array to which pointers is pointing to. The original array ISNT getting reinitialized, its just ignored throughout the entire code.
It is also a memory leak as ATaylor mentions, since you do not delete the allocated space, and cannot delete the space after the function finishes.
To fix everything: just remove the above line.