연락처 생성 함수
Coddy C 여정의 Logic & Flow 섹션에 포함된 레슨 — 63개 중 51번째.
챌린지
쉬움이전 레슨의 Contact 구조체를 바탕으로, 새로운 연락처를 위해 메모리를 동적으로 할당하는 함수를 만드세요. 프로그램은 다음을 수행해야 합니다:
- 이전 레슨과 동일한
Contact구조체 정의를 사용하며, 멤버는 다음과 같습니다:- 크기가 50인 문자 배열
name - 크기가 20인 문자 배열
phone - 크기가 40인 문자 배열
email - 정수형
age
- 크기가 50인 문자 배열
- 다음과 같은 기능을 가진
createContact함수를 작성하세요:- 매개변수를 받지 않음
Contact구조체에 대한 포인터를 반환malloc()을 사용하여 하나의Contact구조체를 위한 메모리를 동적으로 할당- 메모리 할당이 성공했는지 확인:
- 할당에 실패하면 (NULL 반환),
Memory allocation failed를 출력하고 NULL을 반환 - 할당에 성공하면,
Contact created successfully를 출력
- 할당에 실패하면 (NULL 반환),
- 화살표 연산자를 사용하여 모든 구조체 멤버를 기본값으로 초기화:
contactPtr->name[0] = '\0';을 사용하여name을 빈 문자열로 설정contactPtr->phone[0] = '\0';을 사용하여phone을 빈 문자열로 설정contactPtr->email[0] = '\0';을 사용하여email을 빈 문자열로 설정contactPtr->age = 0;을 사용하여age를 0으로 설정
- 새로 생성된 연락처에 대한 포인터를 반환
- 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;
}