2

I have the doubt if calloc initialize to zero all of the elements of a struct array like:

#define MAXDATA    10

struct Est2 {
int dato0;      // Index k
int dato1;      // Index j
int dato2;      // Index i
double dato3;   // Y Coordinate
};

Est2 *myArray = (Est2*) calloc(MAXDATA, sizeof(Est2));

I'm asking this because I don't want the initial data of myArray have garbage or Is there a problem if I don't initialize the array with any value if later in the code I will initialize it anyway for example storing the result of some arithmetical operations? Thanks in advance.

user3517524
  • 21
  • 1
  • 2

2 Answers2

5

From man calloc:

void *calloc(size_t count, size_t size);

The calloc() function contiguously allocates enough space for count objects that are size bytes of memory each and returns a pointer to the allocated memory. The allocated memory is filled with bytes of value zero.

calloc() guarantees that it's going to be pointing at zeroed data.

Leigh
  • 12,038
  • 4
  • 28
  • 36
1

All of the bytes in the structure are set to 0.

This means that the ints have value 0. The double could be a trap , although most common systems use IEEE 754 representation for double, in which the value would be 0.0.

M.M
  • 138,810
  • 21
  • 208
  • 365