[英]C - pointer to array: how to copy just the value (not address) of one pointer to another?
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]
,.... 如果指针pr
指向数组aa = {1, 2, 3, 4, 5, 0, 0, 0, 0, 0}
,那么我们可以通过指针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}
? 如何移动数组(通过指针进行操作),以便获得{1, 1, 2, 3, 4, 5, 0, 0, 0, 0}
? obviously pr[i] = pr[i-1]
won't work. 显然pr[i] = pr[i-1]
不起作用。
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. 我正在使用.Call
为R编写C函数,必须通过这种类型的指针访问C函数中的所有数组。 And I am very confused by the grammar of pointers in C. 我对C语言中的指针语法感到非常困惑。
You basically want to prepend a value, in your example 1
, and remove the last value from the array, in your example a 0
. 您基本上想在示例1
一个值,并从数组中删除最后一个值,在示例1
中为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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.