Language/C
[따배씨] 10.16 다차원 배열을 함수에게 전달해 주는 방법
migrationArc
2021. 6. 8. 14:21
따배씨 - 따라하며 배우는 C언어
10강 배열과 포인터
10.16 다차원 배열 Multidimensional Arrays 을 함수에게 전달해 주는 방법
#include <stdio.h>
#define ROWS 3
#define COLS 4
int sum2d_1(int ar[ROWS][COLS]);
int sum2d_2(int ar[][COLS], int row);
//int sum2d_2(int [][COLS], int row);
//int sum2d_2(int (*ar)[COLS], int col);
int sum2d_3(int* ar, int row, int col);
//int sum2d_3(int*, int, int);
int main(){
int data[ROWS][COLS] = { {1, 2, 3, 4},
{5, 6, 7, 8},
{9, 0, 1, 2} };
printf("%d\n", data[2][3]);
// 2
int* ptr = &data[0][0];
printf("%d\n", *(ptr + 3 + COLS * 2)); // *(ptr + 11)
// 2
printf("Sum of all elements = %d\n",sum2d_1(data));
printf("Sum of all elements = %d\n",sum2d_2(data, ROWS));
printf("Sum of all elements = %d\n",sum2d_3(&data[0][0], ROWS, COLS));
return 0;
}
int sum2d_1(int ar[ROWS][COLS]){
int r, c, tot = 0;
for (r = 0; r < ROWS; r++){
for (c = 0; c < COLS; c++){
tot += ar[r][c];
}
}
return tot;
}
int sum2d_2(int ar[][COLS], int row){
int r, c, tot = 0;
for (r = 0; r < row; r++){
for (c = 0; c < COLS; c++){
tot += ar[r][c];
}
}
return tot;
}
int sum2d_3(int* ar, int row, int col){
int r, c, tot = 0;
for (r = 0; r < row; r++){
for (c = 0; c < col; c++){
tot += *(ar + c + col * r); // ar[c + col * r]
}
}
return tot;
}
int sum2d_1(int ar[ROWS][COLS]);
- prototype 에 배열의 크기를 명시하여도, 함수는 배열의 주소값만 받아와서 사용
int sum2d_2(int ar[][COLS], int row);
int sum2d_2(int [][COLS], int row);
int sum2d_2(int (*ar)[COLS], int col);
- 가장 왼쪽의 index는 생략하고, 추가로 값을 넘겨주는 형식도 가능
int sum2d_2(int (*ar)[COLS], int col);
- 복잡한 표현방법이라 추천하지 않음
- 'COLS 의 개수만큼의 원소를 갖는 배열에 대한 포인터' 라는 의미
int sum2d_3(int* ar, int row, int col);
int sum2d_3(int*, int, int);
- 높은 차원의 배열을 표현 할 때, 많이 사용됨
*(ar + c + col * r); // ar[c + col * r]
- 표현 방법
이 글의 모든 사진과 내용의 출처는 홍정모 교수님께 있음을 알려드립니다.
http://blog.naver.com/atelierjpro
실리콘 밸리의 프로그래머 : 네이버 블로그
안녕하세요! 홍정모 블로그에 오신 것을 환영합니다. 주로 프로그래밍 관련 메모 용도로 사용합니다. 강의 수강하시는 분들은 홍정모 연구소 카페로 오세요.
blog.naver.com
http://www.inflearn.com/course/following-c
홍정모의 따라하며 배우는 C언어 - 인프런 | 강의
'따배씨++'의 성원에 힘입어 새롭게 개발된 C 언어로 시작하는 프로그래밍 입문 강의입니다. '따배씨'와 함께 프로그래밍 인생을 업그레이드 해보세요., 따라하며 배우는 C언어 '따배씨++'의 성원
www.inflearn.com