Search code examples
ccompound-literals

Array type safety function arguments accessed with compound literal


There is a method which is defined in this manner:

void corruption(int (*idata[1]), bool (*flags[3]), bool* (*finfo[2]), int* (*error[1]));

I am trying to pass information to it using compound literals while also respecting type-safety definition, but I have a problem with this.

Argument  (*idata[1])  is information which is being checked.
Argument  (*flags[3]) are information which suggest the method what to do
Argument *(*finfo[2]) are information which are updated by the algorithm changing the original value
Argument *(*error[1]) are information which are updated by the algorithm changing the original value

I do not know how to pass anything to this function via compound literals without producing errors or unwanted behaviour. The reason why I want to try and do this with a compound literal is because I am trying to avoid assigning the information to separate variables since there are variables which already exist in code. I've tried writing this, but of course it does not work.

int data = 5151;
bool f1_flag = false;
bool f2_flag = false;
bool f3_flag = true;
bool* f1_info = points to some variable;
bool* f2_info = points to some variable;
int error_code = 0;

corruption
(
    &(int(*)){ &(int[]){data} },
    &(bool(*)){ &(bool[]){f1_flag, f2_flag, f3_flag} }, 
    &(bool []){ &(bool(*)){ &(bool[]){f1_info, f2_info } } },
    &(int []) { &(int[]){error} }
);

Compiler warnings which I receive for argument 1 and 2 are:

/* warning: initialization of 'int *' from incompatible pointer type 'int (*)[1] */
/* warning: initialization of '_Bool *' from incompatible pointer type '_Bool (*)[3] */

Of course argument 3 and 4 produce warning as well and cause segmentation fault.


Solution

  • I think you do not understand the types well.

    void corruption(int *idata[1], bool *flags[3], bool **finfo[2], int **error[1]);
    
    void foo(void)
    {
    
        int data = 5151;
        bool f1_flag = false;
        bool f2_flag = false;
        bool f3_flag = true;
        bool *f1_info = &f1_flag;
        bool *f2_info = &f2_flag;
        int error_code = 0;
    
        corruption
        (
             (int *[]){&data},
             (bool *[]){&f1_flag, &f2_flag, &f3_flag}, 
             (bool **[]){&f1_info, &f2_info},
             (int **[]){&(int *){&error_code}}
        );
    }