Good day to all
What kind of tradeoffs am i looking at when using either an array or a pointer in a data structure?
Thanks for your time![]()
An array is a vector of values. A pointer is something that refers to a different part of memory (usually dynamically allocated memory but not always). They are totally different things in concept. As it is, arrays are implemented as pointers in C (the pointer is to the first array element). There are no performance benefits to using one over the other because the one is a special case of the other in C (but not necessarily other languages).
Personally I think you can have pointer arithmetic, or good code but never bother at the same time. There is zero reason to use pointer arithmetic, not performance and certainly not readability.
If you doubt this then take a modern compiler, write the same piece of code twice but once using pointer arithmetic and the other using array notation. Then compile them to ASM and compare the output. If the outputs are different at all then get a better compiler and then use array notation.
//edit - if of course you weren't looking for a comparison of array index notation to array pointer notation then ignore all this.//
i was looking for something more along the lines of performance with searching, adding and deleting.
Well you can't add or delete from an array (it has constant size) and a pointer is literally just an address that points to another entity (so search time is constant since a pointer only every points to one thing).
Search time for an array depends on the data. If it is sorted it can be done quickly via a binary search. Otherwise the worse case is linear performance for a linear search (i.e. search time is proportional to the length of the array on average).
If you want fast add, delete and search you are better off with a hash table.
//edit - naturally you will have to find a C implementation of a hash table first.//
Generally, it will depend highly on what you're planning to do. If you're working in C++ then I would use a vector instead of an array, and save pointers for linking data together in things like nodes in linked lists.
There are currently 1 users browsing this thread. (0 members and 1 guests)
Bookmarks