X
xuatla
I encountered "segmentation fault" and I checked my code, found the
following problem:
I want to reallocate memory for an array.
I defined the following function:
int reallocateMemory( double *array, int newsize )
{
if (array) delete[] array;
array = new double[newsize];
return 1;
}
Now,
int main()
{
double *a = new double[2], *b = new double[10];
cout << a << endl; // address of a. (1)
for ( int i = 0; i < 10; i++ ) b = i; // b = {0,1,....,9}
reallocateMemory( a, 10 );
cout << a << endl; // the address of a is same as (1)!
for ( int i = 0; i < 10; i++ ) a = 0.1*i;
for ( int i = 0; i < 10; i++ )
cout << a << " ";
cout << endl; // fine, a is 0,0.1,...,0.9
for ( int i = 0; i < 10; i++ )
cout << b << " ";
cout << endl;
// error: output = 0.3,0.4,...,0.9,7,8,9
return 0;
}
So the memory of "a" is not reallocated although I call the function to
change it.
What I think is that passed-by-pointer in function will change the
parameter directly. Therefore after I call the function
reallocateMemory, "a" should be changed. But it seems that the result is
same as passed-by-value.
What's the problem in my function?
Thank you for your help!
X
following problem:
I want to reallocate memory for an array.
I defined the following function:
int reallocateMemory( double *array, int newsize )
{
if (array) delete[] array;
array = new double[newsize];
return 1;
}
Now,
int main()
{
double *a = new double[2], *b = new double[10];
cout << a << endl; // address of a. (1)
for ( int i = 0; i < 10; i++ ) b = i; // b = {0,1,....,9}
reallocateMemory( a, 10 );
cout << a << endl; // the address of a is same as (1)!
for ( int i = 0; i < 10; i++ ) a = 0.1*i;
for ( int i = 0; i < 10; i++ )
cout << a << " ";
cout << endl; // fine, a is 0,0.1,...,0.9
for ( int i = 0; i < 10; i++ )
cout << b << " ";
cout << endl;
// error: output = 0.3,0.4,...,0.9,7,8,9
return 0;
}
So the memory of "a" is not reallocated although I call the function to
change it.
What I think is that passed-by-pointer in function will change the
parameter directly. Therefore after I call the function
reallocateMemory, "a" should be changed. But it seems that the result is
same as passed-by-value.
What's the problem in my function?
Thank you for your help!
X