c++ initial value of dynamic array

后端 未结 6 711
清酒与你
清酒与你 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 17:47

    I'd advise you to use std::vector<int> or std::array<int,5>

    0 讨论(0)
  • 2020-12-15 17:51

    Value initialize the elements with ()

    Example:

    int *p = new int[10];       // block of ten uninitialized ints
    int *p2 = new int[10]();    // block of ten ints value initialized to 0
    
    0 讨论(0)
  • 2020-12-15 17:52

    I'd do:

    int* a = new int[size];
    memset(a, 0, size*sizeof(int));
    
    0 讨论(0)
  • 2020-12-15 17:57
    int *a=new int[n];
    memset(a, 0, n*sizeof(int));
    

    That sets the all the bytes of the array to 0. For char * too, you could use memset. See http://www.cplusplus.com/reference/clibrary/cstring/memset/ for a more formal definition and usage.

    0 讨论(0)
  • 2020-12-15 17:58

    Sure, just use () for value-initialization:

     int* ptr = new int[size]();
    

    (taken from this answer to my earlier closely related question)

    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题