Dynamic Allocation in C (Answer)
Callocis usually used for dynamic arrays, that is, arrays whose size is not known at compile time.
Malloccan also be used for dynamic arrays.
malloc(m * sizeof (double))instead of
calloc. You must declare
darras a pointer, even though you plan to treat it as an array, because it is dynamically allocated. A declaration in which the size is a variable, as
double darr[m], is not correct C, though gcc apparently permits it.
darrby 25 positions: Assuming the value of
mhas not changed,
reallocrequires the new final size, not an increment. There is no way to recover the original allocated size from
copy = fred, because that does not create an independent copy. You need
+1to allow for the terminator byte. You must use
sizeofbecause it returns the actual length of the string. If
fredis a pointer,
sizeof fredwill give just the size of a pointer, usually too small. If
fredis an array,
sizeof fredwill give the size of the entire array, which may be larger than needed to store the string.
|Pointers and Strings||Question||ADT Declarations in C|