Menu
Coddy logo textTech

連絡先を作成する関数

CoddyのCジャーニー「Logic & Flow」セクションの一部 — レッスン 51/63。

challenge icon

チャレンジ

簡単

前回のレッスンの Contact 構造体をもとに、新しい連絡先のためにメモリを動的に割り当てる関数を作成します。プログラムは以下の要件を満たす必要があります:

  1. 前回のレッスンと同じ Contact 構造体の定義を使用します。メンバーは以下の通りです:
    • サイズ 50 の文字配列 name
    • サイズ 20 の文字配列 phone
    • サイズ 40 の文字配列 email
    • 整数型の age
  2. createContact という名前の関数を作成します。この関数は:
    • 引数を取りません
    • Contact 構造体へのポインタを返します
    • malloc() を使用して、1 つの Contact 構造体に対してメモリを動的に割り当てます
    • メモリ割り当てが成功したかどうかを確認します:
      • 割り当てに失敗した場合(NULL を返した場合)、Memory allocation failed と出力し、NULL を返します
      • 割り当てに成功した場合、Contact created successfully と出力します
    • アロー演算子を使用して、すべての構造体メンバーをデフォルト値に初期化します:
      • contactPtr->name[0] = '\0'; を使用して name を空の文字列に設定します
      • contactPtr->phone[0] = '\0'; を使用して phone を空の文字列に設定します
      • contactPtr->email[0] = '\0'; を使用して email を空の文字列に設定します
      • contactPtr->age = 0; を使用して age を 0 に設定します
    • 新しく作成された連絡先へのポインタを返します
  3. main 関数内で:
    • newContact という名前の Contact 構造体へのポインタを宣言します
    • createContact 関数を呼び出し、返されたポインタを newContact に代入します
    • 連絡先の作成が成功したか確認します:
      • newContact が NULL の場合、Failed to create contact と出力してプログラムを終了します
      • 成功した場合、Contact initialized with default values と出力します
    • アロー演算子を使用して、初期化された連絡先情報を以下の形式で表示します:
      • Default Contact Values:
      • Name: [name] (空になります)
      • Phone: [phone] (空になります)
      • Email: [email] (空になります)
      • Age: [age] (0 になります)
    • free(newContact) を使用して、動的に割り当てられたメモリを解放します
    • Memory freed successfully と出力します

このチャレンジでは、ファクトリ関数(動的に割り当てられた構造体へのポインタを作成して返す関数)の概念を導入します。動的メモリ割り当て、適切なエラーチェック、ポインタを介した構造体の初期化、およびメモリのクリーンアップを練習します。

自分で試してみよう

#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;
}

Logic & Flowのすべてのレッスン