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?
You’re passing in the array pointer by value; this means that when your
doArrayfunction returns, the value inarrinmainis stillNULL– the assignment insidedoArraydoesn’t change it.If you want to change the value of
arr(which is anint *), 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 usingarrto*arr(pointer-dereferencing), and you’ll call it like so:doArray(&arr).Also, in C++ you should really be using
new int[sz]instead ofmalloc.