Function to Create a Contact
Part of the Logic & Flow section of Coddy's C journey — lesson 51 of 63.
Challenge
EasyBuilding on your Contact struct from the previous lesson, create a function that dynamically allocates memory for a new contact. Your program should:
- Use the same
Contactstruct definition from the previous lesson 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
- Write a function named
createContactthat:- Takes no parameters
- Returns a pointer to a
Contactstruct - Uses
malloc()to dynamically allocate memory for oneContactstruct - Checks if the memory allocation was successful:
- If allocation fails (returns NULL), prints
Memory allocation failedand returns NULL - If allocation succeeds, prints
Contact created successfully
- If allocation fails (returns NULL), prints
- Initializes all struct members to default values using the arrow operator:
- Sets
nameto an empty string usingcontactPtr->name[0] = '\0'; - Sets
phoneto an empty string usingcontactPtr->phone[0] = '\0'; - Sets
emailto an empty string usingcontactPtr->email[0] = '\0'; - Sets
ageto 0 usingcontactPtr->age = 0;
- Sets
- Returns the pointer to the newly created contact
- In the main function:
- Declare a pointer to a
Contactstruct namednewContact - Call the
createContactfunction and assign the returned pointer tonewContact - Check if the contact creation was successful:
- If
newContactis NULL, printFailed to create contactand exit the program - If successful, print
Contact initialized with default values
- If
- Display the initialized contact information using the arrow operator in this exact format:
Default Contact Values:Name: [name](will be empty)Phone: [phone](will be empty)Email: [email](will be empty)Age: [age](will be 0)
- Free the dynamically allocated memory using
free(newContact) - Print
Memory freed successfully
- Declare a pointer to a
This challenge introduces the concept of factory functions - functions that create and return pointers to dynamically allocated structs. You'll practice dynamic memory allocation, proper error checking, struct initialization through pointers, and memory cleanup.
Try it yourself
#include <stdio.h>
#include <string.h>
// TODO: Define the Contact struct here
struct Contact {
char name[50];
char phone[20];
char email[40];
int age;
};
int main() {
// TODO: Create a Contact variable named person
struct Contact person;
// Read input values
scanf("%s", person.name);
scanf("%s", person.phone);
scanf("%s", person.email);
scanf("%d", &person.age);
// TODO: Write your validation and output code below
if (person.age < 0 || person.age > 120) {
printf("Invalid age");
return 0;
}
if (strlen(person.phone) < 10) {
printf("Invalid phone number");
return 0;
}
printf("Contact Information:\n");
printf("Name: %s\n", person.name);
printf("Phone: %s\n", person.phone);
printf("Email: %s\n", person.email);
printf("Age: %d\n", person.age);
printf("Name length: %lu\n", strlen(person.name));
if (person.age >= 0 && person.age <= 17) {
printf("Category: Minor");
} else if (person.age >= 18 && person.age <= 64) {
printf("Category: Adult");
} else {
printf("Category: Senior");
}
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