This is actually a much more concise, much more clear question than the one I had asked here before(for any who cares): C Language: Why does malloc() return a pointer, and not the value? (Sorry for those who initially think I’m spamming… I hope it’s not construed as the same question since I think the way I phrased it there made it unintentionally misleading)
-> Basically what I’m trying to ask is: Why does a C programmer need a pointer to a dynamically-allocated variable/object? (whatever the difference is between variable/object…)
If a C programmer has the option of creating just ‘int x’ or just ‘int *x’ (both statically allocated), then why can’t he also have the option to JUST initialize his dynamically-allocated variable/object as a variable (and NOT returning a pointer through malloc())?
*If there are some obscure ways to do what I explained above, then, well, why does malloc() seem the way that most textbooks go about dynamic-allocation?
Note: in the following,
byterefers tosizeof(char)Well, for one,
mallocreturns avoid *. It simply can’t return a value: that wouldn’t be feasible with C’s lack of generics. In C, the compiler must know the size of every object at compile time; since the size of the memory being allocated will not be known until run time, then a type that could represent any value must be returned. Sincevoid *can represent any pointer, it is the best choice.mallocalso cannot initialize the block: it has no knowledge of what’s being allocated. This is in contrast with C++’soperator new, which does both the allocation and the initialization, as well as being type safe (it still returns a pointer instead of a reference, probably for historical reasons).Also,
mallocallocates a block of memory of a specific size, then returns a pointer to that memory (that’s whatmallocstands for: memory allocation). You’re getting a pointer because that’s what you get: an unitialized block of raw memory. When you do, say,malloc(sizeof(int)), you’re not creating aint, you’re allocatingsizeof(int)bytes and getting the address of those bytes. You can then decide to use that block as anint, but you could also technically use that as an array ofsizeof(int)chars.The various alternatives (
calloc,realloc) work roughly the same way (callocis easier to use when dealing with arrays, and zero-fills the data, whilereallocis useful when you need to resize a block of memory).