Function to Populate a Contact
Part of the Logic & Flow section of Coddy's C journey — lesson 52 of 63.
Challenge
EasyBuilding on your contact creation function from the previous lesson, create a function that populates a contact with user input. Your program should:
- Use the same
Contactstruct definition from the previous lessons with members:- A character array
namewith size 50 - A character array
phonewith size 20 - A character array
emailwith size 40 - An integer
age
- A character array
- Use the same
createContactfunction from the previous lesson that:- Dynamically allocates memory for a
Contactstruct - Initializes all members to default values
- Returns a pointer to the contact
- Dynamically allocates memory for a
- Write a function named
populateContactthat:- Takes a pointer to a
Contactstruct as its parameter - Returns nothing (void)
- Prompts the user for input and reads the following data in this exact order:
- Prints
Enter name:and reads a string into the name field usingscanf("%s", contactPtr->name) - Prints
Enter phone:and reads a string into the phone field usingscanf("%s", contactPtr->phone) - Prints
Enter email:and reads a string into the email field usingscanf("%s", contactPtr->email) - Prints
Enter age:and reads an integer into the age field usingscanf("%d", &contactPtr->age)
- Prints
- After reading all input, validates the data:
- If age is less than 0 or greater than 120, prints
Invalid age entered - If phone number length is less than 10 characters (use
strlen()), printsInvalid phone number - If all validations pass, prints
Contact populated successfully
- If age is less than 0 or greater than 120, prints
- Takes a pointer to a
- In the main function:
- Create a contact using the
createContactfunction - Check if contact creation was successful
- Call the
populateContactfunction to fill in the contact data - After populating, display the contact information using the arrow operator in this exact format:
Contact Information:Name: [name]Phone: [phone]Email: [email]Age: [age]
- Free the dynamically allocated memory
- Print
Contact deleted successfully
- Create a contact using the
This challenge demonstrates how to create functions that modify struct data through pointers. The populateContact function receives a pointer to the contact and uses the arrow operator to directly modify the original struct's members. You'll practice user input handling, data validation, and working with dynamically allocated structs through function parameters.
Try it yourself
#include <stdio.h>
#include <stdlib.h>
struct Contact {
char name[50];
char phone[20];
char email[40];
int age;
};
struct Contact* createContact() {
struct Contact* contactPtr = (struct Contact*)malloc(sizeof(struct Contact));
if (contactPtr == NULL) {
printf("Memory allocation failed\n");
return NULL;
}
printf("Contact created successfully\n");
contactPtr->name[0] = '\0';
contactPtr->phone[0] = '\0';
contactPtr->email[0] = '\0';
contactPtr->age = 0;
return contactPtr;
}
int main() {
struct Contact* newContact;
newContact = createContact();
if (newContact == NULL) {
printf("Failed to create contact\n");
return 1;
}
printf("Contact initialized with default values\n");
printf("Default Contact Values:\n");
printf("Name: %s\n", newContact->name);
printf("Phone: %s\n", newContact->phone);
printf("Email: %s\n", newContact->email);
printf("Age: %d\n", newContact->age);
free(newContact);
printf("Memory freed successfully\n");
return 0;
}All lessons in Logic & Flow
1Pointers Fundamentals
What is a Pointer?Declaring PointersThe Address-Of Operator (&)The Dereference Operator (*)NULL PointersRecap: Pointer Basics4Project: Simple Text Utility
Project OverviewCounting Characters2Pointers and Arrays
Array Names as PointersArray Elements - PointersPointer ArithmeticComparing PointersRecap: Pointer Array Traversal5Pointers and Functions
Pass-by-ValuePassing Pointers to FunctionsModifying Vars via PointersA Classic Example: SwapPassing Arrays to FunctionsRecap: Function Pointer Args8Structs and Pointers
Pointers to StructsThe Arrow Operator (->)Passing Structs by ValuePassing Struct PointersDynamic Allocation of StructsRecap: Modifying Struct - Ptr11Final Recap Challenges
Recap: Dynamic String ConcatRecap: Array of StructsRecap: Word Frequency Counter3Character Arrays and Strings
Strings as char ArraysThe Null TerminatorString Input with scanfUsing strlen()Using strcpy()Using strcat()Using strcmp()Recap: Basic String Functions6Memory Management
Stack vs. Heap MemoryDynamic Allocation - malloc()Using sizeof() for AllocationChecking Allocation FailureFreeing Memory with free()Allocating with calloc()Recap: Dynamic Array9Project: Simple Contact Entry
Project: Define Contact StructFunction to Create a Contact