Language/C
[따배씨] 10.18 복합 리터럴과 배열
migrationArc
2021. 6. 8. 14:26
따배씨 - 따라하며 배우는 C언어
10강 배열과 포인터
10.18 복합 리터럴 Compound Literals 과 배열 Arrays
#include <stdio.h>
#define COLS 4
int sum_1d(int arr[], int n);
int sum_2d(int arr[][COLS], int rows);
int main(){
// Literals are constant that aren't symbolic
3;
3.14f;
// compound literal
(int[2]) {3, 4};
return 0;
}
#include <stdio.h>
#define COLS 4
int sum_1d(int arr[], int n);
int sum_2d(int arr[][COLS], int rows);
int main(){
int arr1[2] = {1, 2};
int arr2[2][COLS] = { {1, 2, 3, 4}, {5, 6, 7, 8}};
printf("%d\n", sum_1d(arr1, 2));
printf("%d\n", sum_2d(arr2, 2));
printf("\n");
printf("%d\n", sum_1d((int[2]) {1, 2}, 2));
printf("%d\n", sum_2d((int[2][COLS]){ {1, 2, 3, 4}, {5, 6, 7, 8}}, 2));
printf("\n");
return 0;
}
int sum_1d(int arr[], int n){
int total = 0;
for (int i = 0; i < n; ++i){
total += arr[i];
}
return total;
}
int sum_2d(int arr[][COLS], int rows){
int total = 0;
for (int j = 0; j < rows; ++j){
for (int i = 0; i < COLS; ++i){
total += arr[j][i];
}
}
return total;
}
printf("%d\n", sum_1d((int[2]) {1, 2}, 2));
printf("%d\n", sum_2d((int[2][COLS]){ {1, 2, 3, 4}, {5, 6, 7, 8}}, 2));
- 배열을 선언하지 않고, compound Literal 로 직접 입력
#include <stdio.h>
#define COLS 4
int sum_1d(int arr[], int n);
int sum_2d(int arr[][COLS], int rows);
int main(){
int* ptr1;
int(*ptr2)[COLS];
ptr1 = (int[2]) {1, 2};
ptr2 = (int[2][COLS]) {{1, 2, 3, 4}, {5, 6, 7, 8}};
printf("%d\n", sum_1d(ptr1, 2));
printf("%d\n", sum_2d(ptr2, 2));
return 0;
}
int sum_1d(int arr[], int n){
int total = 0;
for (int i = 0; i < n; ++i){
total += arr[i];
}
return total;
}
int sum_2d(int arr[][COLS], int rows){
int total = 0;
for (int j = 0; j < rows; ++j){
for (int i = 0; i < COLS; ++i){
total += arr[j][i];
}
}
return total;
}
int* ptr1;
int(*ptr2)[COLS];
ptr1 = (int[2]) {1, 2};
ptr2 = (int[2][COLS]) {{1, 2, 3, 4}, {5, 6, 7, 8}};
- 포인터를 선언 후, compound literal 로 초기화
- 이름이 없는 literal data 나 lambda 함수 등을 사용하는 것이 최근 프로그래밍에서 나타나고 있음
이 글의 모든 사진과 내용의 출처는 홍정모 교수님께 있음을 알려드립니다.
http://blog.naver.com/atelierjpro
실리콘 밸리의 프로그래머 : 네이버 블로그
안녕하세요! 홍정모 블로그에 오신 것을 환영합니다. 주로 프로그래밍 관련 메모 용도로 사용합니다. 강의 수강하시는 분들은 홍정모 연구소 카페로 오세요.
blog.naver.com
http://www.inflearn.com/course/following-c
홍정모의 따라하며 배우는 C언어 - 인프런 | 강의
'따배씨++'의 성원에 힘입어 새롭게 개발된 C 언어로 시작하는 프로그래밍 입문 강의입니다. '따배씨'와 함께 프로그래밍 인생을 업그레이드 해보세요., 따라하며 배우는 C언어 '따배씨++'의 성원
www.inflearn.com