Home > Back-end >  How can I Initialize a struct with a function like this (c)
How can I Initialize a struct with a function like this (c)

Time:12-02

When I want to initialize all the components of a struct I do it in the main function like this:

This is the struct:

typedef struct {
    int data[1000];
    int oc;
} Table;

And this is how I initialize all the components to be 0 (the array and the int now are 0 with this)

int main() {
    Table x ={0};

Now I want to do exactly the same but using a function. I want to do something like this:

void initialize(Table *y) {
    y = {0};
}

I think it does not work because to initialize it I should do it when I declare it, so how can I initialize a struct using a function?

CodePudding user response:

Just memset it.

void initialize(Table *y) {
    memset(y, 0, sizeof *y);
}

CodePudding user response:

Remember that y us a pointer so you must dereference it to assign the object itself.

Also you need to tell the compiler that the assignment is from a Table object, which is done with a compound literal.

All in all:

void initialize(Table *y){
    *y = (Table){0};
}

The compound literal creates (Table){0} creates a temporary Table structure object, with the initializer for the structure. Then this temporary structure object is assigned (copied to) the Table structure object that y points to.

It's somewhat similar to the following:

void initialize(Table *y){
    Table temp_struct_object = {0};  // Normal initialization
    *y = temp_struct_object;  // Normal assignment (copy of object)
}
  •  Tags:  
  • c
  • Related