Language/C
[따배씨] 14.10 복합 리터럴
migrationArc
2021. 6. 26. 18:05
따배씨 - 따라하며 배우는 C언어
14강 구조체_1
14.10 복합 리터럴 Compound Literals
#include <stdio.h>
#include <string.h>
#define MAXTITL 41
#define MAXAUTL 31
struct book
{
char title[MAXTITL];
char author[MAXAUTL];
//char* title; // Not recommended
//char* author; // Not recommended
float price;
};
struct rectangle {
double width;
double height;
};
double rect_area(struct rectangle r)
{
return r.width * r.height;
}
double rect_area_ptr(struct rectangle * r)
{
return r->width * r->height;
}
int main()
{
struct book book_to_read = {"Crime and Punishment", "Fyodor Dostoyevsky", 11.25f};
/*
Compound literals
- Temporary structure values
*/
strcpy(book_to_read.title, "Alice in wonderland");
strcpy(book_to_read.author, "Lewis Carroll");
book_to_read.price = 20.3f;
struct book book2 = {"Alice in Wonderland", "Lewis Carroll", 20.3f};
book_to_read = book2;
book_to_read = (struct book){"Alice in Wonderland", "Lewis Carroll", 20.3f};
printf("%s %s\n", book_to_read.title, book_to_read.author);
struct rectangle rec1 = { 1.0, 2.0 };
double area = rect_area(rec1);
area = rect_area((struct rectangle) {1.0, 2.0});
area = rect_area_ptr(&(struct rectangle) {.height = 3.0, .width = 2.0});
// Designated initializers
printf("%f\n", area);
return 0;
}
struct book book_to_read = {"Crime and Punishment", "Fyodor Dostoyevsky", 11.25f};
//book_to_read = {"Alice in Wonderland", "Lewis Carroll", 20.3f}; //Error
- 한번 초기화된 후에는 선언과 같은 방법으로 구조체 값을 변경하지 못함
- 구조체 값 변경 방법
1. member 를 직접 변경
strcpy(book_to_read.title, "Alice in wonderland");
strcpy(book_to_read.author, "Lewis Carroll");
book_to_read.price = 20.3f;
2. 새로운 구조체를 대입하여 변경
struct book book2 = {"Alice in Wonderland", "Lewis Carroll", 20.3f};
book_to_read = book2;
3. 복합 리터럴 구조체로 변경
book_to_read = (struct book){"Alice in Wonderland", "Lewis Carroll", 20.3f};
- 함수에 구조체 입력
1. 구조체 변수를 입력
struct rectangle rec1 = { 1.0, 2.0 };
double area = rect_area(rec1);
2. 복합 리터럴을 입력
area = rect_area((struct rectangle) {1.0, 2.0});
3. 복합 리터럴의 pointer 입력
area = rect_area_ptr(&(struct rectangle) {.height = 3.0, .width = 2.0});
// Designated initializers
- 복합 리터럴은 L-value 이기 때문에, pointer 가 존재
이 글의 모든 사진과 내용의 출처는 홍정모 교수님께 있음을 알려드립니다.
http://blog.naver.com/atelierjpro
실리콘 밸리의 프로그래머 : 네이버 블로그
안녕하세요! 홍정모 블로그에 오신 것을 환영합니다. 주로 프로그래밍 관련 메모 용도로 사용합니다. 강의 수강하시는 분들은 홍정모 연구소 카페로 오세요.
blog.naver.com
http://www.inflearn.com/course/following-c
홍정모의 따라하며 배우는 C언어 - 인프런 | 강의
'따배씨++'의 성원에 힘입어 새롭게 개발된 C 언어로 시작하는 프로그래밍 입문 강의입니다. '따배씨'와 함께 프로그래밍 인생을 업그레이드 해보세요., 따라하며 배우는 C언어 '따배씨++'의 성원
www.inflearn.com