기록
Published 2023. 1. 28. 12:33
[C++] 2차원 배열 초기화 C++
728x90

2차원 배열을 0으로 초기화

#include <iostream>
#define MAX 5

using namespace std;

// 2차원 배열을 0 으로 초기화
int matrix[MAX][MAX] = {0,};

int main(){

    for (int i=0; i<MAX; ++i){
        for (int j=0; j<MAX; ++j){
            cout << matrix[i][j] << " ";
        }
        cout << endl;
    }
    return 0;
}

 

2차원 배열을 0 또는 -1로 초기화

#include <iostream>
#include <string.h>
#define MAX 5

using namespace std;

int matrix[MAX][MAX] = {0,};

int main(){

        // 2차원 배열을 0 또는 -1 로 초기화
    memset(matrix, -1, sizeof(matrix));

    for (int i=0; i<MAX; ++i){
        for (int j=0; j<MAX; ++j){
            cout << matrix[i][j] << " ";
        }
        cout << endl;
    }
    return 0;
}

 

2차원 배열을 특정 값으로 초기화

#include <iostream>
#define MAX 5

using namespace std;

int matrix[MAX][MAX] = {0,};

int main(){

        // 2차원 배열을 특정 값으로 초기화
    fill(&matrix[0][0], &matrix[MAX][MAX], 2);

    for (int i=0; i<MAX; ++i){
        for (int j=0; j<MAX; ++j){
            cout << matrix[i][j] << " ";
        }
        cout << endl;
    }
    return 0;
}

 

출처 : https://wooono.tistory.com/317

'C++' 카테고리의 다른 글

[C++] stack, queue, priority_queue 예제  (0) 2023.06.22
[C++] sort 정렬  (0) 2023.06.22
[C++] Pair  (0) 2023.01.28
[C++] typedef, define  (0) 2023.01.28
[C++] Queue  (0) 2023.01.28
profile

기록

@데굴데구르르 림

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!

2025, 이제 사내 컨플루언스에 모두 작성하게 되어서 업데이트가 잘 없을 것 같습니다..