Home > OS >  C incomplete Type in structs
C incomplete Type in structs

Time:12-04

He folks, i got a problem and a question. Hopefully u can help and explain me.

first of all i have 2 stucts:

typedef struct {
    double x;
    double y;
} A;

typedef struct  {
    unsigned int count;
    A(*stack)[]; 
}B;

this struct B i declare in main() and passing a Pointer of B to a function this will initializ

main(){
    B x;
    function rr(&x);
}

void rr(B* test) {
   test->stack= malloc((4) * sizeof(A)); //4Elements
   for (unsigned int i = 0; i < 4; i  ) {
        (test->stack  i)->x= 89;        
    }
}

on this line (test->stack i)->x= 89; compiler says incomplete Type i know why it is incomplete cause in struct B their is no dimension. but array should initialize in function rr

Maybe u understand what i mean and how to solve my problem. function rr i am not allowed to change.

Greetings

EDIT 1 Thank you for all answers mabey i schould clearify my problem

typedef struct  {
    unsigned int count;
    A(*stack)[]; // here i want a pointer to an array of A's
}B;


//over main it is declared
void rr(B*);


main(){
    B x;
    function rr(&x);
}

// this func is not allowed to change
void rr(B* test) {
   test->stack= malloc((4) * sizeof(A)); //4Elements
   for (unsigned int i = 0; i < 4; i  ) {
        (test->stack  i)->x= 89; // error cause incomplete type but i 
                                 //have to use this line       
    }
}

Hope now it is easier to i understand what i want

CodePudding user response:

This declaration:

A(*stack)[];

Says that stack is a pointer to an array of A of unknown size. That is an incomplete type which means it can't be used directly.

It seems like what you actually want is not a pointer to an array, but a pointer to the first member of a dynamic array of A. So declare the member as a pointer:

A *stack;

CodePudding user response:

In the expression:

(test->stack  i)->x= 89;

before accessing an array via a pointer to an array you must dereference it. Try:

(*test->stack)[i].x= 89;

CodePudding user response:

You do not know how to use flexible array members.

Simply:

typedef struct {
    double x;
    double y;
} A;

typedef struct  {
    size_t count;
    A stack[]; 
}B;


B *createStack(size_t size)
{
    B *s = malloc(sizeof(*s)   size * sizeof( s -> stack[0]));
    return s;
}

void rr(B* test) {
   for (unsigned int i = 0; i < 4; i  ) {
        (test->stack  i)->x= 89;        
    }
}

int main(void)
{
    B *stack = createStack(4);
    rr(stack);
    free(stack);
}

You need only one allocation to mallloc/realloc or free the structure. The array will decay into pointer for your assignment in rr function.

  • Related