'How to change arrangement of element using pointer in c
Here is my code, how can I change line 9 to line 11 in pointer form?
void ShiftRightCircular (ElemType *A, int n, int k) {
/************** begin *****************/
ElemType e;
int p, i = 0;
while (i < n - k) {
p = i / k + 1;
for (int j = 0; j < k ; j++) {
e = A[j]; // line 9
A[j] = A[ (p * k + j) % n]; // line 10
A[ (p * k + j) % n] = e; // line 11
i++;
}
}
/************** end *****************/
}
Solution 1:[1]
array[index] is 100% equivalent to *(array + index)
Candidate replacement:
int d = (p * k + j) % n; // Used to simplify the following:
e = *(A + j); // e = A[j];
*(A + j) = *(A + d); // A[j] = A[ (p * k + j) % n];
*(A + d) = e; // A[ (p * k + j) % n] = e;
Note: (p * k + j) % n better as (1LL * p * k + j) % n to avoid overflow.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | chux - Reinstate Monica |
