简体   繁体   中英

Is it possible to have the same array of pointers to struct point to different types of struct?

I'm working with pointers to structs and have the following set up which has been working.

/* Initialized. */
struct base { ... };  
struct base **db;
db = malloc( base_max * sizeof *db );

/* When a new struct base is required. */
db[ i ] = malloc( sizeof( struct base ) );

Now, if possible, although not really essential, I'd like only db[0] to point to a different struct, struct mem {... } . Is this possible and what is the proper way to do so?

I figured I can set db[0] = malloc( sizeof( struct mem ) ) ; but db is already declared to point to a pointer pointing to a struct base ; and the memory allocation of db is based on that also.

I'm confused because I read pointers must have a type or pointer arithmetic won't work properly; but I also read you don't have to cast the pointers from malloc even though it returns void pointers.


Regarding the duplicate question, although it discusses void type it doesn't answer my question of how to accomplish this or the risks of it. The comment by @4386427 appears to point to the real issue to be considered which isn't addressed in the other question or the one answer to this one. Thank you.

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] , ie, dereferencing it, you need to cast it to the proper pointer type (ie, 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM