Ok, so I am basically making a function that resizes the size of the array at run time. Please see the following code, it is working perfectly.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
|
#include <iostream>
#include <string>
using namespace std;
int* resize(int *p, int &size)
{
int *temp = new int[size + 1];
for (int i = 0; i < size; i++)
temp[i] = p[i];
size++;
delete[]p;
return temp;
}
int main()
{
int *p = NULL;
bool fh = true;
int size = 0;
while (fh)
{
cout << "Enter Number: ";
p = resize(p, size);
cin >> p[size-1];
cin.ignore();
if (p[size - 1] == -1)
fh = false;
}
cout << endl << endl;
for (int i = 0; i < size; i++)
cout << p[i] << " ";
getchar();
return 0;
}
|
Now, in the above code, I returned the new formed array (with increased size)
Please see the following code now,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
|
#include <iostream>
#include <string>
using namespace std;
void resize(int *p, int &size)
{
int *temp = new int[size + 1];
for (int i = 0; i < size; i++)
temp[i] = p[i];
size++;
delete[]p;
p = temp;
}
int main()
{
int *p = NULL;
bool fh = true;
int size = 0;
while (fh)
{
cout << "Enter Number: ";
resize(p, size);
cin >> p[size-1];
cin.ignore();
if (p[size - 1] == -1)
fh = false;
}
cout << endl << endl;
for (int i = 0; i < size; i++)
cout << p[i] << " ";
getchar();
return 0;
}
|
This above code is exactly similar to the last one, however there is no returning of pointer from function and instead I am assigning the new array's pointer to my original pointer within that function. But it is giving error, apparently because it can't access that memory...
The problem here is, from what I understand, whenever you pass an argument by "pointer" (like I did with the array here), the argument variable gets updated within that function.
Considering the same concept, this second code also should work and the value of the original pointer (i.e. p) should get updated, but it isn't doing that. Can I know what's the issue here?