c ++动态数组的初始值 [英] c++ initial value of dynamic array

查看:99
本文介绍了c ++动态数组的初始值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要动态创建一个整数数组。我发现使用静态数组时的语法

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

int a [5]={0};

正确将所有元素的值初始化为0。

initializes correctly the value of all elements to 0.

创建动态数组时是否有类似方法

Is there a way to do something similar when creating a dynamic array like

int* a = new int[size];

而不必遍历数组的所有元素?还是用for循环分配值仍然是最佳选择?
谢谢

without having to loop over all elements of the a array? or maybe assigning the value with a for loop is still the optimal way to go? Thanks

推荐答案

当然,只需将()用于值初始化:

Sure, just use () for value-initialization:

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

(取自此答案是我之前密切相关的问题)

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

这篇关于c ++动态数组的初始值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆