Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
353 views
in Technique[技术] by (71.8m points)

c - 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...