如何用另一种(也许更短的)方式写这个?
有没有更好的方法来初始化C中分配的数组?
有没有更好的方法来初始化C中分配的数组?
int main(void) { int* a; a = new int[10]; for (int i=0; i < 10; ++i) a[i] = 0; }
解决方法
int *a =new int[10](); // Value initialization
ISO C第8.5 / 5节
To value-initialize an object of type T means:
— if T is a class type (clause 9) with a user-declared constructor (12.1),then the default constructor for T is called (and the initialization is ill-formed if T has no accessible default constructor);
— if T is a non-union class type without a user-declared constructor,then every non-static data member and base-class component of T is value-initialized;
— if T is an array type,then each element is value-initialized;
— otherwise,the object is zero-initialized
对于零初始化,值初始化和默认初始化之间的差异,请阅读this