The purpose of the Copy
function in the following code is to copy an array of integers from one array to another using C but the output seems wrong.
What could be the problem here?
#include <iostream>
using namespace std;
void Copy(int old_array[],int new_array[],int length)
{
int *ptr1 = old_array;
int *ptr2 = new_array;
int i = 0;
for(int i=0 ; i<length ; i )
{
*(ptr2 ) = *(ptr1 );
}
for (int i = 0; i <2; i )
{
cout<<*(ptr2 i)<<endl;
}
}
int main()
{
int a[2]={0,1};
int b[2];
Copy(a,b,2);
}
This is the output:
CodePudding user response:
ptr2
is one past the end of the array when your print loop runs.
Try this:
void Copy(int old_array[], int new_array[], int length)
{
int* ptr1 = old_array;
int* ptr2 = new_array;
int i = 0;
for (int i = 0; i < length; i )
{
*(ptr2 ) = *(ptr1 );
}
ptr2 = new_array;
for (int i = 0; i < 2; i )
{
cout << *(ptr2 i) << endl;
}
}
CodePudding user response:
Your ptr2
is pointing to the element b[2]
(which is out-of-bound access) at the time you are printing it in the second for loop.
You can fix it by subtracting the length
from the ptr2
in the second for loop like below.
#include <iostream>
using namespace std;
void Copy(int old_array[],int new_array[],int length)
{
int *ptr1 = old_array;
int *ptr2 = new_array;
int i = 0;
for(int i=0 ; i<length ; i )
{
*(ptr2 ) = *(ptr1 );
}
for (int i = 0; i <2; i )
{
cout<<*(ptr2 i - length)<<endl;
}
}
int main()
{
int a[2]={0,1};
int b[2];
Copy(a,b,2);
}
CodePudding user response:
The copy seems fine but the second for is accessing ptr2 which was incremented in the first for and is point to some invalid memory position. You could use new_array in this second loop. I suppose this second loop is only for debug and will be better located in the main using, in you case, the variable b.