0

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?

2
  • There is no point passing a struct to a function if you are going to treat it as a local variable and overwrite whatever was in it. Commented Dec 1, 2021 at 18:06
  • Yes it is a pointer I have just changed it Commented Dec 1, 2021 at 18:06

2 Answers 2

6

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)
}
Sign up to request clarification or add additional context in comments.

6 Comments

And it is usually the most efficient way as well (assuming compiler optimizations enabled)\
This method is only to initialize structs or can it be used in arrays like this(It doesn´t work so how can I use that method to initialize whatever I want but not doing it in the declaration as the first example I have put? int main(){ int table[5]; table = table{0};
@Tenko Arrays can't be assigned to from the beginning, only copied to.
@Tenko It's possible to create array like that as well, for example (int[5]){1, 2, 3, 4, 5}. But as mentioned it's not possible to assign to array.
``` int main(){ int table[5]; int table2[5]={0}; table=table2; ``` To assign to array you mean doing this? Why this can not be done as the structs?
|
6

Just memset it.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.