Make Unreal REAL.
article thumbnail
Published 2023. 3. 20. 21:34
동적 할당 시 0으로 초기화 C++/기타

 

C언어에서는 calloc() 함수로 0으로 초기화된 메모리를 할당 받을 수 있다.

 

#include <stdio.h>
#include <stdlib.h>

void main()
{
    int i;
    int *arr = (int*)calloc(5, sizeof(int));
    
    for (i = 0; i < 5; ++i)
        printf("%d ", arr[i]);
        
    free(arr);
    arr = NULL;

    return 0;
}

 

출력

0 0 0 0 0

 

 

How to initialise memory with new operator in C++?

I'm just beginning to get into C++ and I want to pick up some good habits. If I have just allocated an array of type int with the new operator, how can I initialise them all to 0 without looping th...

stackoverflow.com

위 쓰레드에 따르면 C++에서는 아래처럼 new 키워드를 통한 할당 뒤에 ()를 붙여 0으로 초기화된 메모리를 할당 받는 것은 공식적으로 인정된 방법이라고 한다.

 

#include <iostream>

using namespace std;

void main()
{
    int *arr = new int[5]();
    
    for (int i = 0; i < 5; ++i)
        cout << arr[i] << " ";
        
    delete[] arr;
    arr = nullptr;

    return 0;
}

 

출력

0 0 0 0 0

'C++ > 기타' 카테고리의 다른 글

if 조건문에서 지역 변수 선언  (0) 2023.05.06
정수 표기법(Literal)  (0) 2023.04.19
콤마(,) 연산자  (0) 2023.03.20
람다 식에서 [this] 캡처  (0) 2023.03.15
클래스 전방 선언(Forward declaration)  (0) 2023.03.07
profile

Make Unreal REAL.

@diesuki4

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

검색 태그