요약: String Wrapper
Coddy C 여정의 객체 지향 프로그래밍 섹션에 포함된 레슨. 61개 중 16번째.
챌린지
쉬움동적으로 할당된 문자 배열을 감싸는 StringObject 모듈을 만들어 봅시다. 이 복습 과제에서는 메모리를 안전하게 관리하기 위한 완전한 객체 수명 주기, 생성자, 읽기 전용 메서드 및 소멸자를 함께 구현합니다.
다음 세 파일을 만듭니다:
stringobj.h: 단일 멤버인char *text(동적으로 할당된 string을 가리키는 pointer)를 포함하는StringObjectstruct를 Declare합니다. 또한 다음 세 function을 Declare합니다:create_string:const char *input을 받아 새로 할당된 StringObject를 가리키는 pointer를 returns합니다.print_string:const StringObject *를 받아 저장된 텍스트를 displays합니다.free_string:StringObject *를 받아 할당된 모든 memory를 해제합니다.
STRINGOBJ_Hsymbol을 사용하여 include guards를 사용합니다.stringobj.c: 세 function을 모두 Implement합니다. 생성자는 먼저 struct를 위한 memory를 Allocate한 다음, text를 위한 memory를 Allocate하고(strlen에 null terminator를 위한 1을 더해야 함을 기억하세요), input string을 Copy해야 합니다. 소멸자는 역순으로 Free해야 합니다. 먼저 내부textbuffer를 Free한 다음 struct itself를 Free합니다. safety를 위해 소멸자에 NULL Check를 포함하세요.main.c: 모듈을 사용하여 string object를 Create하고, 내용을 Print한 다음, 적절히 정리합니다.
저장할 하나의 input, 즉 text string을 받습니다.
main file에서 제공된 텍스트로 StringObject를 Create하고, 내용을 Print하고, memory를 Free한 다음, confirmation message를 Print합니다.
print_string function은 다음 format으로 출력해야 합니다:
Text: {text}Free한 후 다음을 Print합니다:
Freed예를 들어 input이 Hello World인 경우 출력은 다음과 같습니다:
Text: Hello World
Freed직접 해보기
#include <stdio.h>
#include "stringobj.h"
int main() {
char input[256];
fgets(input, sizeof(input), stdin);
// 개행 문자가 있으면 제거
int len = 0;
while (input[len] != '\0') len++;
if (len > 0 && input[len - 1] == '\n') {
input[len - 1] = '\0';
}
// TODO: Create a StringObject with the input text
// TODO: print_string을 사용하여 문자열 출력
// TODO: Free the StringObject using free_string
// TODO: 정리 확인을 위해 "Freed" 출력
return 0;
}
객체 지향 프로그래밍의 모든 레슨
직접 연습해 보세요: 온라인 C 컴파일러