I am trying to write the following code using pointers instead of indexing (in C
ID: 3784724 • Letter: I
Question
I am trying to write the following code using pointers instead of indexing (in C++). The following code is correct:
void shift(int arr[], int n) {
int temp = arr[n - 1];
int temp1;
for (int i = 0; i < n; i++) {
temp1 = arr[i];
arr[i] = temp;
temp = temp1;
}
}
This is my ATTEMPT at writing it with pointers but I know it is wrong. Can someone help fix it?
void shift(int arr[], int n) {
int temp = arr + (n - 1);
int temp1;
for (int *ptr = arr; ptr < arr + n; ++ptr) {
temp1 = *ptr;
*ptr = temp;
temp = temp1;
}
}
Explanation / Answer
void shift(int *a, int n){
int temp= *(a+n-1);
int temp1;
for(int i=0;i<=n;i++){
temp1=*(a+i);
*(a+i)=temp;
temp=temp1;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.