I'm making a function in C++ that takes an array and the size of the array as the parameters. The function is supposed to create a new array twice the size of the received one. Then it should copy the elements from the first array into the new one and fill the remaining slots in the array with 0.
int main()
{
// get number between 0 and 50 from user, n
// for (i = 0; i < n; i++):
// append random number (0 - 1000) to dataList array
int * newList = myFunction(dataList, n, z);
// NEWLIST TEST
cout << "newlist address: " << newList << endl;
for (int i = 0; i < n * 2; i++)
{
cout << newList[i] << " ";
}
cout << endl;
///////////////
for (int i = 0; i < n * 2; i++)
{
cout << newList[i] << endl;
}
}
int * myFunction(int x[], int y)
{
int z[y * 2];
for (int i = 0; i < y; i++)
{
z[i] = x[i];
}
for (int i = 0; i < y; i++)
{
z[i + y] = 0;
}
// Z TEST
cout << "z address: " << z << endl;
for (int i = 0; i < y * 2; i++)
{
cout << z[i] << " ";
}
cout << endl;
///////////
return z;
}
I output the addresses of newlist (in main) and z (in myFunction) to test if the addresses are the same, and they are.
I also output the contents of the address while in myFunction and while in main. The contents of Z are correct, 4 random numbers and 4 zeroes. However, the contents of newList are always different and unpredictable, which leads me to believe the memory for the address of z is cleared once the function ends.
How do I make this where the contents of the address of newList are kept as they are before the function ends?