Reputation: 503
As I continue learning the C language I got a doubt. Which are the differences between using an array in which each element is an struct and using an array in which each element is a pointer to the same type of struct. It seems to me that you can use both equally (Although in the pointers one you have to deal with memory allocation). Can somebody explain me in which case it is better to use one or the other?
Thank you.
Upvotes: 9
Views: 6024
Reputation: 144740
Arrays of structures and arrays of pointers to structures are different ways to organize memory.
Arrays of structures have these strong points:
struct s *p = calloc(n, sizeof(*p));
.struct s *prev = p - 1, *next = p + 1;
They also have disadvantages:
p[i].member
generates a multiplication, which may be costly on some architectures if the size of the structure is not a power of 2.Using an array of pointers has these advantages:
NULL
. This convention is used for the argv[]
array of command line arguments provided to the main()
function.NULL
pointer values could be used to specify missing elements.p[i].member
generates a simple shift and an extra memory access, but may be more efficient than the equivalent expression for arrays of structures.and the following drawbacks:
EDIT: As hinted by David Bowling, one can combine some of the advantages of both approaches by allocating an array of structures on one hand and a separate array of pointers pointing to the elements of the first array. This is a handy way to implement a sort order, or even multiple concomitant sort orders with separate arrays of pointers, like database indexes.
Upvotes: 12