Thread: Array index vs. direct pointer

  1. #1
    Registered User
    Join Date
    Jan 2013
    Posts
    11

    Array index vs. direct pointer

    I am very new to C coding, but I have worked with other languages in other operating environments. Please forgive me if I ask a stupid question!?!

    Generally speaking, in C, is it generally more efficient to load a set of values into an array and access them in the code via indices, or is it better to malloc them into memory and address them directly?

    I would think that the array and the indices would add additional instructions in the compile that would make a high volume process noticeably slower.

    Please advise - many kind thanks!!!

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by dtkokovoko
    Generally speaking, in C, is it generally more efficient to load a set of values into an array and access them in the code via indices, or is it better to malloc them into memory and address them directly?
    Other than syntax, there should be no difference between the use of an index and the use of a pointer, assuming that you are using an optimising compiler. As for the difference between using an array and malloc: there is likely to be a small runtime penalty for the malloc call, but then typically more space can be allocated with malloc (unless you're dealing with an array with static storage duration), if you need it, and it is possible to realloc. In a sense, you will be "address(ing) them directly" either way.

    Quote Originally Posted by dtkokovoko
    I would think that the array and the indices would add additional instructions in the compile that would make a high volume process noticeably slower.
    You can always measure and find out.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    It is generally more efficient to write code that is easiest for mere mortals to understand, and therefore easiest to get right, than indulging - as you are - in premature optimisation.

    The answer to your question (which is more efficient) is really "they're generally the same but, if there is any difference, it depends" anyway. There is no general answer that is applicable across all possible ways of coding such things up, that works on all compilers, that work with all compiler optimisation settings.

    It is not often that the eventual gains from such tweaking will exceed the cost of a few hours of programmer effort (even if we assume a low hourly rate) to implement it.

    You might save a few microseconds or milliseconds per access, so you should only worry about such things if it has been demonstrated (eg by performance benchmarking and profiling) that the performance of the code really matters. Humans are notoriously ineffective at identifying the hotspots in their code, notoriously over-confident in their ability to do so, and inclined to spend hours of their time for small gains. In the quest for "efficiency", many programmers introduce more problems (bugs, untested failure conditions, etc) into their code - which means their code may be efficient and give the wrong results.

    Starting without having identified hotspots in your code, and pursuing some generic thing called "efficiency", is a therefore waste of time.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  4. #4
    Registered User
    Join Date
    Jan 2013
    Posts
    11
    Quote Originally Posted by laserlight View Post
    ... In a sense, you will be "address(ing) them directly" either way.

    You can always measure and find out.
    As far as addressing is concerned, I wasn't aware of how direct or indirect the array index method might be by comparison, and, while measurement (inspection) is always useful after the fact, I thought a bit of prevention might useful.
    Last edited by dtkokovoko; 01-07-2013 at 09:35 PM.

  5. #5
    Registered User
    Join Date
    Jan 2013
    Posts
    11
    Thank you for your wise guidance!!! Your message is so relevant and so valid in so many contexts that it is almost painful...

    As a newcomer, however, I cannot help noticing how seemingly inscrutable most "great" C code is. I do not think this is accidental, but I hope it is more for the art than for the artifice.

    Take the counter++ example: cool idea!!!, but does it come before or after it is referenced, and is it like any other language? No. Is that good or bad? Who is to say? Certainly, not me... But, to your point, how easy is it for mere mortals (like me) to "get it"? It feels like a wall, and a moat...

  6. #6
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Other than programming guys and gals, people don't like using pointers. Their blood pressure rises dangerously just mentioning the term. Use indices. Under the hood, it's all done with pointers anyway but the additional clarity is *considerable*. You won't see a difference in the run-time, because both indices and pointers, wind up being pointers or offsets to pointers.

  7. #7
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    Truly great C code is not inscrutable.

    It is one thing for a programmer with years of experience to understand the code written by another programmer with years of experience. It is quite another for a programmer with a few days or weeks of experience to understand code written by a programmer with years of experience. There is a whole bunch of knowledge that the experienced programmer has, and makes use of. Without that knowledge, the novice programmer will find the code harder to read.

    IMHO, the problem needs to be addressed on three fronts. The first is that experienced programmers need to put in the time to avoid embedding obscure assumptions into their code unless they make the effort to clearly describe and justify those assumptions. Code that is written so only the three most experienced developers can understand it in a team of 500 is not good code.

    The second is that novices need to spend time solving problems (writing code and documenting how it works), reading widely so they learn more about (in this case) C, and also some effort dissecting code written by others. Yes, some of that code will be terrible and some will be great. They key - when looking at other people's code - is forming your own opinions (What is this code doing? Why is it doing it this way and not that way? Would I do it that way? Why or why not? What approach would I use?)

    The third is that people need to persist, because nothing comes easy the first time.


    These things don't come easy. That's life. A native speaker of another language who wants to work with native english speakers will need to put in the effort - trial, error, false starts, etc - to learn english. Similarly, if an english speaker wants to work with people who speak another language. Both will find some basic things (basic grammar, a few key words that are often used) easy, but will trip up on more advanced things. It's the same thing with developing software. The only difference is that people, for some reason, expect software development to keep being easy.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  8. #8
    Registered User
    Join Date
    Jan 2013
    Posts
    11
    Adak -

    Is there a way to manage dynamic string arrays other than with pointers?

    It would certainly be a welcome alternative!!!
    Last edited by dtkokovoko; 01-07-2013 at 10:39 PM.

  9. #9
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Quote Originally Posted by dtkokovoko View Post
    Adak -

    Is there a way to manage dynamic string arrays other than with pointers?

    It would certainly be a welcome alternative!!!
    First, understand that chars are just a bunch of chars - and not a string in C, unless they end with a null character to mark that end of the string: '\0' .

    When you have a string, you can do string operations:
    copy, print, concatenate one string onto another, get it's length, etc.

    Pointers to strings are very handy in C, consider:

    Code:
    words[2][20]={{"Alfa"},{"Bravo"}};
    
    for(int i=0;i<2;i++) 
       printf("%s\n",words[i]);
    words[i] is a pointer to the first letter of each word, and since they are strings - C will give them the end of string char for you here - you can easily print them using %s.

    But in general, I wouldn't use pointers for anything you do in arrays. Yes, it has some short and sweet C expressions , but overall, use indices - you will be glad you did.

  10. #10
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    Quote Originally Posted by dtkokovoko View Post
    I would think that the array and the indices would add additional instructions in the compile that would make a high volume process noticeably slower.
    From what I've read over the years, that used to be true more often than not. However over the years things have changed and more recently I've read that because the compiler must often assume that the pointer could point to anything, that it has less room for optimisation there. I've also read that the cost of code that does array indexing has changed with different processors as well.

    Really, if everything I've read is to be believed, its just too close to call any more. Simply don't wory about it.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  11. #11
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    Quote Originally Posted by dtkokovoko View Post
    I would think that the array and the indices would add additional instructions in the compile that would make a high volume process noticeably slower.
    From what I've read over the years, that used to be true more often than not. However over the years things have changed and more recently I've read that because the compiler must often assume that the pointer could point to anything, that it has less room for optimisation there. I've also read that the cost of code that does array indexing has changed with different processors as well.

    Really, if everything I've read is to be believed, its just too close to call any more. Simply don't wory about it.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  12. #12
    Registered User
    Join Date
    Nov 2012
    Posts
    1,393
    Quote Originally Posted by Adak View Post
    Other than programming guys and gals, people don't like using pointers. Their blood pressure rises dangerously just mentioning the term. Use indices.
    Here is a simple test program

    Code:
    #include <stdio.h>
    
    #ifdef USE_MYSTRCPY_V1
    void mystrcpy(char *dest, char *src) 
    {
        while (*src != '\0') {
            *dest = *src;
            dest++;
            src++;
        }
    }
    #endif
    
    #ifdef USE_MYSTRCPY_V2
    void mystrcpy(char *dest, char *src) 
    {
        int i = 0;
        int j = 0;
        while (src[i] != '\0') {
            dest[i] = src[i];
            i++;
            j++;
        }
    }
    #endif
    
    int main(void)
    {
        char srcbuf[100] = "Hello, world!";
        char destbuf[100] = "";
        mystrcpy(destbuf, srcbuf);
        printf("%s\n", destbuf);    
        return 0;
    }
    Compile with:
    gcc -Wall -DUSE_MYSTRCPY_V1 -std=c99 -Os -o v1 example.c
    gcc -Wall -DUSE_MYSTRCPY_V2 -std=c99 -Os -o v2 example.c

    Observations:
    1. On MinGW GCC 4.7.2, assembler output of "mystrcpy" for both v1 and v2 is identical.
    2. Compiling with other options for -O produces longer assembly for the index version.
    3. "Programming guys and gals" that know C or C++ to a usable level should find the pointer version no less readable than the index version.
    4. With too many indices, one can easily prefer the pointer version to the index version.

    I think it comes down to an issue of style and what makes most sense. In this example, I find the pointer version to make the most sense. I personally don't really care about observationa 1 and 2, but just included them for interest's sake.
    Last edited by c99tutorial; 01-08-2013 at 05:43 AM.

  13. #13
    Registered User
    Join Date
    Jan 2013
    Posts
    11
    So, to summarize what I think I understand from the collective response is make the code understandable first, try to avoid using pointers unless you really need to (simplifying string handling, managing allocated memory, etc.), and try to balance use of pointer and indices. Only carry fine tuning further when performance and measurement dictate. Does that sum it up pretty well?

    Thank you ALL for your responses!!! I will try to make a meaningful contribution to the effort...

  14. #14
    Master Apprentice phantomotap's Avatar
    Join Date
    Jan 2008
    Posts
    5,108
    make the code understandable first
    O_o

    Always! Code should always be understandable.

    Write clear, consistent, and semantically meaningful code.

    try to avoid using pointers unless you really need to
    O_o

    You'd get fired for that nonsense if you worked for me.

    I realize this is the C area, but I'm still going to say it: the C++ standard library is built on the iterator concept. (The iterator concept could be viewed as a generalization of C pointers.) If you plan on learning C++ eventually, you'd probably benefit from the exposure.

    Only carry fine tuning further when performance and measurement dictate.
    Add: "and only if you've examined alternative algorithmic strategies"

    Soma

  15. #15
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    Sorry, I've no idea how I ended up with a duplicate post above as I did not post twice. I think IE must have done a dirty on me with that random question that sometimes comes up asking if I want to stay on the same page or leave the page. That question never makes sense so I don't know how to answer it. I just want it to do what it normally does!
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 8
    Last Post: 04-04-2012, 09:03 PM
  2. Replies: 1
    Last Post: 08-12-2011, 03:07 AM
  3. Pointer index wierd output:
    By Configure in forum C Programming
    Replies: 6
    Last Post: 09-12-2008, 01:12 AM
  4. index array
    By kurz7 in forum C Programming
    Replies: 9
    Last Post: 04-24-2003, 08:57 AM
  5. About Array Index
    By Kokila in forum C Programming
    Replies: 3
    Last Post: 11-08-2001, 12:29 PM