developer tip

C ++에서 동적 배열을 어떻게 초기화합니까?

optionbox 2021. 1. 5. 07:58
반응형

C ++에서 동적 배열을 어떻게 초기화합니까?


이 정적 배열 초기화의 동적 동등성을 어떻게 달성합니까?

char c[2] = {};  // Sets all members to '\0';

즉, 모든 값이 종료 문자로 초기화 된 동적 배열을 만듭니다.

char* c = new char[length]; // how do i amend this? 

char* c = new char[length]();

두 가지 방법:

char *c = new char[length];
std::fill(c, c + length, INITIAL_VALUE);
// just this once, since it's char, you could use memset

또는:

std::vector<char> c(length, INITIAL_VALUE);

두 번째 방법으로 기본 두 번째 매개 변수는 이미 0이므로 귀하의 경우에는 불필요합니다.

std::vector<char> c(length);

[편집 : Fred의 답변에 투표하기 char* c = new char[length]();]


어쩌면 사용 std::fill_n()할까요?

char* c = new char[length];
std::fill_n(c,length,0);

new-expression의 배열 형식은 이니셜 라이저의 한 형식 인 비어있는 (). 이 BTW는 {}비 동적 초기화에서 비어있는 것과 동일한 효과를 갖습니다 .


위의 내용은 C ++ 11 이전 언어에 적용됩니다. C ++ 11부터는 배열 new-expression과 함께 균일 한 초기화 구문을 사용할 수 있습니다.

char* c = new char[length]{};
char* d = new char[length]{ 'a', 'b', 'c' };

C ++에는이를 수행하는 특정 기능이 없습니다. 그러나 배열 대신 std :: vector를 사용하는 경우 (아마도해야하는 것처럼) 벡터를 초기화 할 값을 지정할 수 있습니다.

std::vector <char> v( 100, 42 );

모든 값이 42로 초기화 된 크기 100의 벡터를 생성합니다.


한 줄로 쉽게 할 수 없습니다. 넌 할 수있어:

char* c = new char[length];
memset(c, 0, length);

또는 새 연산자를 오버로드 할 수 있습니다.

void *operator new(size_t size, bool nullify)
{
    void *buf = malloc(size);

    if (!buf) {
             // Handle this
    }

    memset(buf, '\0', size);

    return buf;
}

그러면 다음을 수행 할 수 있습니다.

char* c = new(true) char[length];

동안

char* c = new char[length];

이전 행동을 유지할 것입니다. (참고로, 모든 news가 생성 한 것을 0으로 만들려면 위와 동일하지만 bool nullify부분 을 제거하면 됩니다.)

Do note that if you choose the second path you should overload the standard new operator (the one without the bool) and the delete operator too. This is because here you're using malloc(), and the standard says that malloc() + delete operations are undefined. So you have to overload delete to use free(), and the normal new to use malloc().

In practice though all implementations use malloc()/free() themselves internally, so even if you don't do it most likely you won't run into any problems (except language lawyers yelling at you)


Since c++11 we could use list initialization:

char* c = new char[length]{};

For an aggregate type, then aggregate initialization will be performed, which has the same effect like char c[2] = {};.


and the implicit comment by many posters => Dont use arrays, use vectors. All of the benefits of arrays with none of the downsides. PLus you get lots of other goodies

If you dont know STL, read Josuttis The C++ standard library and meyers effective STL


No internal means, AFAIK. Use this: memset(c, 0, length);


you have to initialize it "by hand" :

char* c = new char[length];
for(int i = 0;i<length;i++)
    c[i]='\0';

ReferenceURL : https://stackoverflow.com/questions/2029651/how-do-you-initialise-a-dynamic-array-in-c

반응형