In majority of the architecture, the size of a pointer (to any type) is constant, and any pointer type will generally occupy the same amount of memory.
Unless you're on some really uncommon hardware/platform, you can assign db[0]
with any pointer returned by malloc()
using a different structure type used for sizing calculation altogether.
db[0] = malloc( sizeof( struct mem ));
should do good, you just need to worry about memory leak, as you'll be overwriting the previous memory location returned by malloc()
.
However, since you're storing a pointer to memory of a differnt type, while using db[0]
, i.e., dereferencing it, you need to cast it to the proper pointer type (i.e., struct mem*
) before you can use the pointer to access /operate based on the struct mem
type.
That said,
I'm confused because I read pointers must have a type or pointer arithmetic won't work properly;
That's true
but I also read you don't have to cast the pointers from malloc even though it returns void pointers.
Also true, as when you assign the pointer to a variable of a certain type (other than void
), the conversion is implicit. You can use that variable to perform pointer arithmetic.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…