c++ initial value of dynamic array

后端 未结 6 713
清酒与你
清酒与你 2020-12-15 17:12

I need to dynamically create an array of integer. I\'ve found that when using a static array the syntax

int a [5]={0};

initializes correctl

6条回答
  •  不思量自难忘°
    2020-12-15 18:00

    To initialize with other values than 0,

    for pointer array:

    int size = 10;
    int initVal = 47;
    int *ptrArr = new int[size];
    std::fill_n(ptrArr, size, initVal);
    std::cout << *(ptrArr + 4) << std::endl;
    std::cout << ptrArr[4] << std::endl;
    

    For non pointer array

    int size = 10;
    int initVal = 47;
    int arr[size];
    std::fill_n(arr, size, initVal);
    

    Works pretty Much for any DataType!

    !Be careful, some compilers might not complain accessing a value out of the range of the array which might return a non-zero value

提交回复
热议问题