Home  >  Article  >  Backend Development  >  How to Efficiently Initialise Arrays Allocated with the `new` Operator in C ?

How to Efficiently Initialise Arrays Allocated with the `new` Operator in C ?

Linda Hamilton
Linda HamiltonOriginal
2024-11-16 13:40:03345browse

How to Efficiently Initialise Arrays Allocated with the `new` Operator in C  ?

Initialising Memory with New Operator in C

Query:

Beginning C learners often wonder about the best practices for initialising arrays allocated with the new operator. Is it preferred to manually loop through and set each element to 0, or is there a more efficient method?

Answer:

Surprisingly, C offers a dedicated syntax for value-initialising arrays:

new int[10]();

It's crucial to include the empty parentheses; using (0) or other inputs would not work with this technique.

This behaviour is outlined in ISO C 03 5.3.4[expr.new]/15, which specifies that a new expression with a () initialiser will perform value-initialisation, regardless of the array type.

By contrast, the (expression-list) form of initialisation comes with restrictions that disallow array types.

The above is the detailed content of How to Efficiently Initialise Arrays Allocated with the `new` Operator in C ?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn