C (not C++): passing a pointer passed to a function to another function

I know, questions about "passing pointers to functions" are not rare on SE, but the questions I found unfortunately didn't help me to solve my problem.

I have the below function in C that is supposed to parse a float value from a buffer (char array) and assign it to a corresponsing float variable:

void read_float_from_buffer(float *var, char *buffer, uint8_t start, uint8_t end) {
    char val_buf[8];

    // transfer characters representing float to a temporary buffer
    uint8_t p=0;
    for (uint8_t i=start;i<=end && p<7;i++) {
        val_buf[p++]=buffer[i];
    }
    val_buf[p]='\0';

    // perform sscanf on this temporary buffer
    float buf=-1;
    if(sscanf(val_buf, "%.2f", &buf)==1) // this fails, sscanf returns 0
      *var=buf;
}

I have another function find_float_in_buffer() which searches a char buffer for the start and end indices of a float value. The function read_float_from_buffer() is called within this function:

float a_float_variable=0.;
void find_float_in_buffer(char *buffer) {
    uint8_t start,end=0;
    /*
    I do some magic here to find out where my float string starts and ends
    */
    read_buffer_float(&a_float_variable,buffer,start,end);
    }
}

From my understanding this should work, but for some reason, scanning the val_buf temporary buffer fails (sscanf returns 0).

My question: is the way I'm passing the reference to buffer to read_buffer_float in find_float_in_buffer correct? I thought I finally understood how to pass pointers or references to functions, but I'm not sure if this is how you would pass a pointer in a function on to another function.



Read more here: https://stackoverflow.com/questions/67392247/c-not-c-passing-a-pointer-passed-to-a-function-to-another-function

Content Attribution

This content was originally published by Sim Son at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: