Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I Initialize a struct with a function like this (c)

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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)
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading