Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C pointer arithmetic applied to function argument

I have a pointer to an array element which is used as an argument in a function and is moved along the array inside said function via the "++" operation. I would like the updated position of the pointer to be re-used after the function’s completion.

The following code contains two attempts to solve the issue. The first attempt – via move_pointer function – was expanding on an answer to a similar question. Unfortunately, it does not seem to work, the function argument seems unaffected.
The second attempt – via move_pointer_func function – works as intended, but I see no way to expand the solution to the case of moving two such pointers at once. As a result, I would appreciate any advice on how the result can be achieved with modifying move_pointer function instead.

#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;
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The postfix increment operator ++ has higher precedence than the unary dereference opererator *. So this:

*pointer++;

Parses as this:

*(pointer++);

Which just increments the local variable. You want to dereference first, then increment:

(*pointer)++;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading