Search code examples
cdata-structuresheaderstructure

Howw to dynamically set size of an array in an header file from outside the header file in c?


//stack.h 
struct stack{
    int top;
    char data[];   //set the size of this array
}s;

void init(){    
    s.top = -1;
}

int isFull(){
    return (s.top==MAX-1) ? 1 : 0;
}

 int isEmpty(){
    return (s.top==-1) ? 1 : 0;
}   

void push(char ch){
    if(!isFull()){
        s.data[++s.top] = ch;
    }else{
        printf("\n The stack is full\n");
    }
}

 char pop(){
    return (!isEmpty()) ? s.data[s.top--] : '\0';
}

I want to implement this stack in an header file and want to set the size of the data array from outside.I Know this is an header file and its of no use if we change the header variables, but still am curious.


Solution

  • You structure contains what is called a flexible array member. Such a structure can be created by dynamically allocating space for the struct plus the desired size of the flexible array member.

    struct stack{
        int top;
        char data[];
    } *s;
    
    void initStack()
    {
        s = malloc(sizeof(struct stack) + MAX * sizeof(char));
    }