有没有更好的方法来初始化C中分配的数组?

前端之家收集整理的这篇文章主要介绍了有没有更好的方法来初始化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

原文链接:https://www.f2er.com/c/117310.html

猜你在找的C&C++相关文章