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.
It is not possible to create an array of pointer to structures.
Pointer to structure holds the add of the entire structure. It is used to create complex data structures such as linked lists, trees, graphs and so on. The members of the structure can be accessed using a special operator called as an arrow operator ( -> ).
Pointer is a variable which holds the address of another variable of its type and points to the variable and can be used to read and write to that variable by dereferencing. Structs are data structures. Pointer to structure is a pointer which holds the address of a structure.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With