Reputation: 111
If a pointer pr
points to an array aa = {1, 2, 3, 4, 5, 0, 0, 0, 0, 0}
, then we can access the array through the pointer pr[0]
, pr[1]
, pr[2]
,....
How can I shift the array (operated through the pointer) such that I can get{1, 1, 2, 3, 4, 5, 0, 0, 0, 0}
? obviously pr[i] = pr[i-1]
won't work.
Here is my code:
#include <stdio.h>
int main() {
int aa[10] = {1, 2, 3, 4, 5, 0, 0, 0, 0, 0};
int i, m, *pr = aa;
printf("\n pr[0] = %d, pr[1] = %d, pr[2] = %d, pr[3] = %d", pr[0], pr[1], pr[2], pr[3]);
for(i = 0; i < 9; i++) {
m = *(pr + i);
pr[i+1] = m;
}
printf("\n \n pr[0] = %d, pr[1] = %d, pr[2] = %d, pr[3] = %d \n", pr[0], pr[1], pr[2], pr[3]);
printf("\n \n aa[0] = %d, aa[1] = %d, aa[2] = %d, aa[3] = %d \n", aa[0], aa[1], aa[2], aa[3]);
return(1);
}
I am writing a C function for R using .Call
, all the arrays in the C function have to be accessed through this type of the pointers. And I am very confused by the grammar of pointers in C.
Upvotes: 0
Views: 1229
Reputation: 2469
You basically want to prepend a value, in your example 1
, and remove the last value from the array, in your example a 0
.
If you take a look at what happens you will see the following:
position: 0 1 2 3 4 5 6
starting: { a0 a1 a2 a3 a4 a5 a6 }
\ \ \ \ \ \
final: { b0 a0 a1 a2 a3 a4 a5 }
So you want to do as you proposed shifting each value, but you have to start at the end (or you will overwrite everything with the same value).
for(i = 9; i > 0; i--) {
pr[i]=pr[i-1];
}
pr[0] = NEWVALUE;
Upvotes: 1