0

I am writing a program for address book. There are insert, display and delete options. In insertion, it takes input data and stores them to a file. whenever I add new contact it adds them to the file. After saving the data to file, Can i dynamically allocate an array of struct addressbook to store each contact details. So that if I want to display or delete a particular contact it will be easy other than opening a file, comparing each element in the file. Depending upon the number of contacts saved into the file, can we dynamically allocate array for struct addressbook and store the details.

    #define FIRST_NAME_LENGTH  15
    #define LAST_NAME_LENGTH   15
    #define NUMBER_LENGTH      15
    #define ADDRESS_LENGTH     15
    /* Structure defining a name */
    struct Name
    {
      char lastname[LAST_NAME_LENGTH];
      char firstname[FIRST_NAME_LENGTH];
    };

    /* Structure defining a phone record */
    struct addressbook 
    {
      char answer;
      struct Name name;
      char address[ADDRESS_LENGTH];
      char phonenumber[NUMBER_LENGTH];

    };
    struct addressbook a;


    void add_record()
    {
      printf("enter details\n");
      printf("enter lastname of person :\n");
      scanf("%s", a.name.lastname);
      printf("enter firstname of person :\n");
      scanf("%s", a.name.firstname);
      printf("enter address of person :\n");
      scanf("%s", a.address);
      printf("enter phone number of person :\n");
      scanf("%s", a.phonenumber);
      if((fp = fopen(filename,"a+")) == NULL){
        printf("Error opening %s for writing. Program terminated.\n", filename);
        abort();
      }
      fwrite(&a, sizeof(a), 1, fp);                  /* Write to the file */
      fclose(fp);                                     /* close file */
      printf("New record added\n");
    }

1 Answer 1

1

Your address book is supposed to hold a list of contacts. So its better not to clutter it with specific Contact details. A better way to do this would be:

struct Contact
{
  struct Name name;
  char address[ADDRESS_LENGTH];
  char phonenumber[NUMBER_LENGTH];
};

In your AddressBook structure you can store objects of Struct Contact either as a linked list or an array( dynamically growing if you need it).

struct AddressBook
{
  Contact *contacts[MAX_CONTACTS];
}

Everytime you read in data, store it into a new Contact object and store the pointer to that object in your array. But if you have large no of contacts, it is not recommended to store all of them in memory, rather you can do some binary search on the file and read only the needed block of contacts.

Sign up to request clarification or add additional context in comments.

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.