Noah Pereira
Noah Pereira

Reputation: 19

Clear all values within a nested struct passed to a function by address

Here are my structures:

struct Name {
    char firstName[31];
    char middleInitial[7];
    char lastName[36];
};

struct Contact
{
    struct Name name;
};

I have an array of Contact structures which is passed by address to this function:

void updateContact(struct Contact contacts[], int size)
{
        // More code up here that deals with finding the index 
        // and such

        contacts[index].name = { 0 }; // Expected an expression before {
}

The name struct is populated with data and I would simply like to reinitialize all values contained so I can create new data.

Upvotes: 0

Views: 243

Answers (3)

user3629249
user3629249

Reputation: 16540

regarding:

contacts[index].name = { 0 };

this only works during initialization and this statement is an assignment.

Suggest:

memset( contacts[ index ].name, 0, sizeof( contacts[ index ].name ) );

However, to clear ALL the fields in the struct suggest:

memset( contacts[ index ], 0, sizeof( contacts[ index] ) );

However, to clear the whole array suggest:

memset( contacts, 0, sizeof( contacts ) );

Upvotes: 0

Ishan Patel
Ishan Patel

Reputation: 21

I would suggest you do it using malloc so you can easily free the memory using free(pointer);

Change your struct to this:

struct Name {
    char* firstName;
    char* middleInitial;
    char* lastName;
};

This is for when you make the struct:

Name name;
name.firstName = (char*) malloc(sizeof(char) * 31);

//REPEAT FOR THE OTHER STRINGS

free(name.firstName);
free(name.middleInitial);
free(name.lastName);

Upvotes: -2

rtx13
rtx13

Reputation: 2610

You can zero out one contact like this:

        memset(contacts[index].name, 0, sizeof contacts[index].name);

This will result in all strings being zero-length.


Alternatively you can assign NUL just to the first character of each string like this, but this requires that you know and track all members of struct Name:

        contacts[index].name.firstName[0] = '\0';
        contacts[index].name.middleInitial[0] = '\0';
        contacts[index].name.lastName[0] = '\0';

Alternatively your compiler may support this syntax:

        contacts[index].name = (struct Name){ 0 };

Upvotes: 3

Related Questions