Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic memory allocation - default-initialization of primitive types in c++

If I allocate an array of some primitive type e.g.

double *v = new double[10];

I need to know, what the inital value of the array entries will be.

Is it specified in the standard or compiler dependend and where can I find it.

Thanks, Johannes

like image 553
Johannes Gerer Avatar asked May 30 '11 12:05

Johannes Gerer


People also ask

Is there dynamic memory allocation in C?

The “malloc” or “memory allocation” method in C is used to dynamically allocate a single large block of memory with the specified size. It returns a pointer of type void which can be cast into a pointer of any form.

Which operator is used in C to allocate memory dynamically?

C uses the malloc() and calloc() function to allocate memory dynamically at run time and uses a free() function to free dynamically allocated memory. C++ supports these functions and also has two operators new and delete, that perform the task of allocating and freeing the memory in a better and easier way.

What is the syntax of dynamic memory allocation in C?

C Program : // C Program to dynamically allocate an int ptr #include <stdio.h> #include <stdlib.h> int main() { // Dynamically allocated variable, sizeof(char) = 1 byte. char *ptr = (char *)malloc(sizeof(char)); if (ptr == NULL) { printf("Memory Error!\n"); } else { *ptr = 'S'; printf("%c", *ptr); } return 0; }


1 Answers

No, the array contents are not initialized. You need to use double *v = new double[10](); to have the default value of 0 for each element (Notice ()).

like image 76
Naveen Avatar answered Oct 01 '22 12:10

Naveen