This is algorithm for removing duplicate elements from array:
#include <stdio.h>
int main() {
int i, n = 5, j, k, arr[5] = {1, 2, 1, 2, 4};
for (i = 0; i < n; i ) {
for (j = i 1; j < n; j ) {
if (arr[i] == arr[j]) {
for (k = j; k < n - 1; k ) {
arr[k] = arr[k 1];
}
n--;
j--;
}
}
}
for (i = 0; i < n; i )
printf("%d ", arr[i]);
return 0;
}
How could this be written with pointer arithmetic?
I need something like this:
int *p=arr;
while(p<arr n){
p ;
}
CodePudding user response:
arr[i]
can be replaced by *(arr 1)
, example, this would be pointer notation, I would advise against this as it makes the code harder to read.
This is just a matter of coding style, it's two different ways of doing the same thing.
If you were to replace int arr[5]
by int *arr = malloc(sizeof *arr * 5)
you could still use both notations, your code would still work perfectly as it is as you can see here, only this time you would be working on block of memory pointed by arr
and thus you would be doing pointer arithmetic.
CodePudding user response:
By replacing Arr[x]
with *(p x)
, p
is the array's pointer and x is the index.
#include <stdio.h>
int main()
{
int i, n=5, j, k, arr[5]={1,2,1,2,4}, *p=arr;
for (i = 0; i < n; i ) {
for (j = i 1; j < n; j ) {
if (*(p i)==*(p j)) {
for (k = j; k < n - 1; k ) {
*(p k) = *(p k 1);
}
n--;
j--;
}
}
}
for(i=0;i<n;i )
printf("%d ", *(p i));
return 0;
}