I'm new to c++ and as an exercise trying to print an array using a function. I created two arrays arr
and arr2
as following.
int main(){
int arr[5] = {11, 12, 13, 14, 15};
int i =1;
int* arr2 = &i;
*arr2 =1;
*(arr2+1) =2;
*(arr2+2) =3;
*(arr2+3) =4;
*(arr2+4) =5;
printArray(arr2,5);
printArray(arr,5);
}
I'm trying to print those two arrays using the function below.
void printArray(int arr[],int size){
for(int i=0; i<size; i++){
cout<<*(arr+i)<<" ";
}
cout<<endl;
}
The result after running the program is,
1 2 3 4 5
2 3 4 5 15
But the expected result is,
1 2 3 4 5
11 12 13 14 15
Can someone explain what is happening here, If it is a problem with memory allocation highly appreciate if you can explain with a proper diagram.