c++/문법

2차원 배열 파라미터로 넘기기

로봇0301 2022. 11. 11. 22:40

C언어 2차원 배열 파라미터로 넘기기 - 제타위키 (zetawiki.com)

C언어 2차원 배열 파라미터로 넘기기

1 개요

C언어 2차원 배열 파라미터로 넘기기

2 int a[3][3] ★★

C
CPU
0.1s
MEM
18M
0.1s
 
 Copy
#include<stdio.h>
void print(int a[3][3]) {
    for(int i=0; i<3; i++) {
        for(int j=0; j<3; j++) printf("%d ", a[i][j]);
        printf("| ");
    }
}
int main() {
   int arr[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
   print(arr); // 1 2 3 | 4 5 6 | 7 8 9 | 
}
1 2 3 | 4 5 6 | 7 8 9 | 

3 int a[][3] ★★

C
CPU
0.0s
MEM
18M
0.1s
 
 Copy
#include<stdio.h>
void print(int a[][3]) {
    for(int i=0; i<3; i++) {
        for(int j=0; j<3; j++) printf("%d ", a[i][j]);
        printf("| ");
    }
}
int main() {
   int arr[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
   print(arr); // 1 2 3 | 4 5 6 | 7 8 9 | 
}
1 2 3 | 4 5 6 | 7 8 9 | 

4 int (*a)[3] ★

C
CPU
0.0s
MEM
18M
0.1s
 
 Copy
#include<stdio.h>
void print(int (*a)[3]) {
    for(int i=0; i<3; i++) {
        for(int j=0; j<3; j++) printf("%d ", a[i][j]);
        printf("| ");
    }
}
int main() {
   int arr[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
   print(arr); // 1 2 3 | 4 5 6 | 7 8 9 | 
}
1 2 3 | 4 5 6 | 7 8 9 | 

5 int* a

C
CPU
0.0s
MEM
18M
0.1s
 
 Copy
#include<stdio.h>
void print(int* a) {
    for(int i=0; i<3; i++) {
        for(int j=0; j<3; j++) printf("%d ", *(a+i*3+j));
        printf("| ");
    }
}
int main() {
   int arr[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
   print((int*)arr); // 1 2 3 | 4 5 6 | 7 8 9 | 
}
1 2 3 | 4 5 6 | 7 8 9 | 
C
CPU
0.0s
MEM
18M
0.1s
 
 Copy
#include<stdio.h>
void print(int* a) {
    int (*b)[3] = (void*) a;
    for(int i=0; i<3; i++) {
        for(int j=0; j<3; j++) printf("%d ", b[i][j]);
        printf("| ");
    }
}
int main() {
   int arr[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
   print((int*)arr); // 1 2 3 | 4 5 6 | 7 8 9 | 
}
1 2 3 | 4 5 6 | 7 8 9 | 

6 void* a ★★

C
CPU
0.0s
MEM
18M
0.1s
 
 Copy
#include<stdio.h>
void print(void* a) {
    for(int i=0; i<3; i++) {
        for(int j=0; j<3; j++) printf("%d ", *((int*)a+i*3+j));
        printf("| ");
    }
}
int main() {
   int arr[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
   print((void*)arr); // 1 2 3 | 4 5 6 | 7 8 9 | 
}
1 2 3 | 4 5 6 | 7 8 9 | 
C
CPU
0.0s
MEM
18M
0.1s
 
 Copy
#include<stdio.h>
void print(void* a) {
    int (*b)[3] = a;
    for(int i=0; i<3; i++) {
        for(int j=0; j<3; j++) printf("%d ", b[i][j]);
        printf("| ");
    }
}
int main() {
   int arr[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
   print((void*)arr); // 1 2 3 | 4 5 6 | 7 8 9 | 
}
1 2 3 | 4 5 6 | 7 8 9 |