我有一个指向数组元素的指针,该指针用作函数中的参数,并通过“++”操作沿所述函数内的数组移动。我希望在函数完成后重新使用指针的更新位置。
以下代码包含解决该问题的两次尝试。第一次尝试 - 通过
move_pointer
函数 - 扩展了 类似问题的答案。不幸的是,它似乎不起作用,函数参数似乎不受影响。
第二次尝试 - 通过 move_pointer_func
函数 - 按预期工作,但我认为没有办法将解决方案扩展到同时移动两个此类指针的情况。因此,如果有任何有关如何通过修改 move_pointer
函数来实现结果的建议,我将不胜感激。
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
void move_pointer(const double** pointer){
*pointer++;
}
const double* move_pointer_func(const double* pointer){
pointer++;
return pointer;
}
void check_pointer_movement(const double* input_vec, const int ndim, const bool use_func) {
const double* input_vec_pointer=&input_vec[0];
for (int i = 0; i!=ndim; i++){
printf("%e\n", *input_vec_pointer);
if (use_func){
input_vec_pointer=move_pointer_func(input_vec_pointer);
}
else {
move_pointer(&input_vec_pointer);
}
}
}
int main() {
int ndim=4;
double input_vec[4]={0.25, 0.65, 0.95, 1.2};
printf("First attempt:\n");
check_pointer_movement(input_vec, ndim, false);
printf("Second attempt:\n");
check_pointer_movement(input_vec, ndim, true);
return 0;
}
后缀增量运算符
++
的优先级高于一元解引用运算符 *
。所以这个:
*pointer++;
解析如下:
*(pointer++);
这只是增加局部变量。您想先取消引用,然后增加:
(*pointer)++;