type casting void pointer to struct type

11,470

[] operator has a higher precedence that a (cast) operator. Thus you have to use additional parenthesis:

 S2[0] = ((myStruct *)Array1)[0];

or use a pointer:

myStruct* a = Array1 ;
S2[0] = a[0];
Share:
11,470
SSS
Author by

SSS

Updated on June 04, 2022

Comments

  • SSS
    SSS almost 2 years

    How do I type cast a void pointer to a struct array? Here is my code:

    typedef struct{
        int   a;
        double b;
    } myStruct;
    
    void Func1(void * Array1);
    
    int main(){
        myStruct S1[5];
    
        S1[0].a = 1;
        S1[0].b = 2.3;
    
        S1[1].a = 2;
        S1[1].b = 3.4;
    
        Func1(S1);
    
        return 0;
    }
    
    void Func1(void * Array1){
        myStruct S2[5];
    
        S2[0] = (myStruct *)Array1[0];
    }
    

    I get compile errors in Func1 for assigning S2[0]. How do I typecast the Array1 correctly?

  • Deduplicator
    Deduplicator over 9 years
    or the dereference-operator instead.