微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

有没有更好的方法来初始化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.jb51.cc/c/117310.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐