C++ 배열 초기값 채우기

1 개요[ | ]

C++ 배열 초기값 채우기

2 1차원 배열[ | ]

값을 넣지 않은 경우
#include <iostream>
using namespace std;
int main() {
    int A[5];
    for(int i=0; i<5; i++) cout << A[i] << ' '; // 0 0 2111058512 22062 0 
}
→ 쓰레기값이 들어 있을 수 있다.
모두 0으로 채우기
#include <iostream>
using namespace std;
int main() {
    int A[5] = {};
    for(int i=0; i<5; i++) cout << A[i] << ' '; // 0 0 0 0 0 
}
#include <iostream>
#include <cstring>
using namespace std;
int main() {
    int A[5];
    memset(A, 0, sizeof(A));
    for(int i=0; i<5; i++) cout << A[i] << ' '; // 0 0 2111058512 22062 0 
}
개별 값을 넣은 경우
#include <iostream>
using namespace std;
int main() {
    int A[5] = {1, 2, 3, 4, 5};
    for(int i=0; i<5; i++) cout << A[i] << ' '; // 1 2 3 4 5 
}

3 2차원 배열[ | ]

값을 넣지 않은 경우
#include <iostream>
using namespace std;
int main() {
    int A[3][4];
    for(int i=0; i<3; i++) {
        for(int j=0; j<4; j++) cout << A[i][j] << ' ';
        cout << endl;
    }
}
→ 쓰레기값이 들어 있을 수 있다.
모두 0으로 채우기
#include <iostream>
using namespace std;
int main() {
    int A[3][4] = {};
    for(int i=0; i<3; i++) {
        for(int j=0; j<4; j++) cout << A[i][j] << ' ';
        cout << endl;
    }
}
개별 값을 넣은 경우
#include <iostream>
using namespace std;
int main() {
    int A[3][4] = { {11,12,13,14}, {21,22,23,24}, {31,32,33,34} };
    for(int i=0; i<3; i++) {
        for(int j=0; j<4; j++) cout << A[i][j] << ' ';
        cout << endl;
    }
}

4 같이 보기[ | ]

문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}