Initialising Memory with the New Operator in C
In C , the new operator allocates memory dynamically. Newcomers often face the challenge of efficiently initialising allocated memory without resorting to manual looping. This question explores the optimal way to accomplish this task.
Memset vs. C Syntax
One option is to use memset, a function that sets a block of memory to a specified value. However, C provides a more elegant solution for value-initialisation:
new int[10]();
This syntax initialises an array of type int with ten elements, all set to 0. It utilises the special syntax () to signal value-initialisation.
ISO C Standard
The ISO C 03 standard explicitly allows this behaviour in section 5.3.4[expr.new]/15. It states that a new-expression with an initialiser of the form () initialises the object with the value initialiser (8.5). This includes arrays without any restrictions.
Advantages
This syntax simplifies initialisation, especially for large arrays. It also ensures proper value-initialisation, which is important for correctness and avoiding undefined behaviour. As a result, it is recommended as the "C " way to initialise memory allocated with new.
The above is the detailed content of How Do You Efficiently Initialize Memory Allocated with the `new` Operator in C ?. For more information, please follow other related articles on the PHP Chinese website!