I am reading about the realloc function, i.e.
void *realloc(void *ptr, size_t size);
and the author of the textbook I'm reading (K.N. King "C Programming a Modern Approach", 2nd edition, p.421, last paragraph), at some point writes
Although
reallocdoesn't require thatptrpoint to memory that's being used as an array, in practice it usually does.
My apologies if this is trivial, but I'm confused. My obvious question is: how? Unfortunately, the author doesn't go any further on this.
Can you provide an expanded explanation, perhaps using a simple example?
The “it” in “in practice it usually does” means
ptr. The clause is saying that we usually usereallocwith memory that is being used as an array.The most common use of
reallocis to reallocate space for an array: We initially allocate some memory, process input, find that processing the input requires a larger array, and so usereallocto increase the space. This is not a requirement ofrealloc; it is the nature of how it is used.It is not the only possible use. Another is we might have some set of related structures, such as
struct Square,struct Circle,struct Polygon, and so on, all with some common initial element,struct Shape. We might initially allocate space forstruct Shapeso that we can do some initial processing of the shape before we know what shape it will be. Later, when the specific shape is done, we might usereallocto grow the space from that needed forstruct Shapeto that needed forstruct Square.