[Solved] Deleting all structure entries in C Programming


The members of struct person are fixed in size, and are not allocated separately from the struct instance – short answer is that you cannot resize the arrays, nor can you deallocate their storage without deallocating the entire struct instance. The absolute best you can do in this case is to write an empty string to each member to indicate it’s not in use:

strcpy( contacts[i].fname, "" );

This does not change the size of the array, though.

In order to make the members of struct person resizable and/or deletable, you have to allocate them separately from the struct instance itself. To do that, you need to declare them as pointers to char, as opposed to arrays of char:

struct person
{
  char *fname;
  char *lname;
  char *number;
};

When you create a new instance of struct person, you will need to allocate the memory for each member separately:

#define SIZE 20  // for this example, both number of contacts and size
                 // of each struct member

struct person contacts[size];
for ( size_t i = 0; i < j; i++ )
{
  contacts[i].fname = malloc( sizeof *contacts[i].fname * SIZE );
  contacts[i].lname = malloc( sizeof *contacts[i].lname * SIZE );
  contacts[i].number= malloc( sizeof *contacts[i].number * SIZE );
}

To resize any of the members, use realloc:

 char *tmp = realloc( contacts[i].fname, sizeof *contacts[i].fname * SIZE * 2 );
 if ( tmp ) contacts[i].fname = tmp;

Since realloc can potentially return NULL, it’s recommended that you save the result to a temporary pointer variable, rather than immediately re-assigning it back to your original pointer; otherwise you risk losing track of the previously-allocated memory, leading to a memory leak.

You are also going to want to track how much memory is allocated for each member so you guard against buffer overruns.

To delete any of the members, use free:

free( contacts[i].fname );

Note that if you dynamically allocate an instance of struct person, you still need to dynamically allocate each member:

struct person *p = malloc( sizeof *p );
p->fname = malloc( sizeof *p->fname * SIZE );
...

This also means that you must deallocate each member before you deallocate the struct instance itself:

free( p->fname );
free( p->lname );
free( p->number );
free( p );

Simply freeing p will not free the memory allocated to p->fname, p->lname, and p->number.

2

solved Deleting all structure entries in C Programming