Reputation: 1
I'm trying to create arrays of doubles in C, such that every array has d doubles in it (the user inputs d). I tried using calloc to allocate the memory for each array:
double *vec;
vec = (double*) calloc(d, sizeof(double));
For some reason it only generates arrays of doubles of size 8 (i.e. it generates a "blank" array of size 8 with only zeroes in it: [0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000]).
I even tried putting a specific number in the calloc call (for example, 3) - but still it only returns an array of size 8.
Upvotes: -3
Views: 70
Reputation: 223795
calloc
does not return an array. It returns a pointer. The pointer points to the first byte of memory that has been reserved in response to the calloc
request.
The reservation is invisible. You cannot see how much space is reserved.1 A memory reservation is implemented by accounting in internal data structures shared by malloc
, calloc
, realloc
, free
, and related routines.
Because calloc
clears the memory it reserves, if n bytes are requested and granted, the first n bytes of memory at the pointed-to address will contain zeros. Bytes beyond that may or may not contain zeros, because calloc
does not guarantee anything about the contents of memory beyond that or whether it is reserved for use or not.
The fact that the contents of memory beyond the first n bytes do or do not contain zeros cannot be used to determine that that memory was or was not allocated or prepared by calloc
.
1 Some C implementations may provide routines that report information about how much space is reserved and/or may provide documentation about how much space is reserved. For example, an implementation may document that each reservation is padded to a multiple of 16 bytes.
Upvotes: 1