0

I am using another programmer's component which demands a struct. the component is being updated once in a while and I want to validate there are no field I missing when I fill it up. I was thinking about it that way:

    typedef struct //this is from the component's lib
{
    float FrequencyMax;
    float FrequencyAvg;
    float PwrTotal;
    float Vgrid;
    float IappTot;
    float IapparentMax;
    float CurrentPhi;
}XApcInputs;

    


    XApcInputs APC_input;
    Apc_InterfaceIterInitStruct(&APC_input);    //init struct
    Apc_InterfaceIterArrangeStruct(&APC_input); //arrange with real values
    if(Apc_InterfaceIterValidStruct(&APC_input))   //validation
       APC_MainIter(&APC_input); //using component

how can I run over all addresses (when I know they are all float) inside the array by the size. Ive tried this:

void Apc_InterfaceIterInitStruct(XApcInputs *APC_input)
{
    float* FirstAddres = APC_input;
    float* LastAddres = APC_input+sizeof(XApcInputs)/sizeof(float);
    while((FirstAddres++)!=LastAddres)
    {
        *FirstAddres = MAX_FLOAT;
    }
}

bool Apc_InterfaceIterValidStruct(XApcInputs *APC_input)
{
    float* FirstAddres = APC_input;
    float* LastAddres = APC_input+sizeof(XApcInputs)/sizeof(float);
    while((FirstAddres++)!=LastAddres)
    {
        if(*FirstAddres == MAX_FLOAT)
            return false;
    }
    return true;
}

what do I miss? I still trying to practice and learn how to work with pointers

GBasi
  • 1
  • 1
  • It can't be done... at least not in a standard compliant way – Support Ukraine Oct 20 '21 at 09:16
  • The end address should be simply `APC_input + 1`. However, this assumes that the struct length, including any padding, is always divisible by the size of a float. – Arkku Oct 20 '21 at 09:16
  • You could simply assert `sizeof(thestruct) == whatever you expect right now`. This should fire if fields are added or removed. – Mat Oct 20 '21 at 09:19
  • As an unrelated comment, the naming here is quite bad: you have inconsistent styles with snake_case and CamelCase, sometimes the `APC` is all in caps, sometimes `Apc`. Both "addres" variables are missing an "s" (should be "address"). And of course you are using the "first" address as an iterator so that it isn't the first address anymore. And your "last" address is not the last valid address, but the end address that is no longer valid. – Arkku Oct 20 '21 at 09:21
  • Unrelated: Even if this was compliant code, your code never writes MAX_FLOAT to the first member. Further it writes after the last member. – Support Ukraine Oct 20 '21 at 09:21
  • Also, neither this or the approach of asserting the size of the struct to be as expected can handle a change that kept the same number of floats but renamed them (e.g., remove 1 field, add 1 field). I think the correct solution is to assert the size _and_ manually refer to every field by name so that it will fail to compile if the names do not match. – Arkku Oct 20 '21 at 09:24

0 Answers0