Thread: arrays and pointers

  1. #1
    Registered User
    Join Date
    Jan 2002
    Posts
    52

    arrays and pointers

    given
    double ar[20];

    and a function call
    function(ar,size);

    is this equivalent to
    function(&ar[0],size)
    ?????

    whats the difference between
    function(ar+1,size)
    and
    function(&ar[1],size)
    ????

  2. #2
    Davros
    Guest
    Presumably, your function declaration would look like this:

    void function(double* ar, int size);

    In this case, the calls:


    function(ar, 20);

    and

    function (&ar[0], 20);


    are equivelent. In both cases you are passing a pointer to the first element in an array of 20 doubles. In the second case, you have de-referenced the first element to a double, and then re-referenced it to a pointer with the & character.

    You can use this technique to pass a pointer to the second character (as your example):

    function(&ar[1], 19);

    Notice I have decremented the size value, as there are only 19 elements in the array pointed to by &ar[1].

    The 'function(ar+1,size)' looks incorrect. Remember ar is an 'address' of an array of doubles, not a double itself.

  3. #3
    Unregistered
    Guest
    The 'function(ar+1,size)' looks incorrect. Remember ar is an 'address' of an array of doubles, not a double itself.

    function(ar+1, size-1);
    is the same as
    function(&ar[1], 19);

    the 'ar+1' increments the address stored in ar by the size of 1 double.

  4. #4
    Davros
    Guest
    OK, I take it back. &ar[1] & ar + 1 are equivalent in that case. Never used that notation before.

  5. #5
    Registered User larry's Avatar
    Join Date
    Sep 2001
    Posts
    96
    Just a note. Things like
    Code:
    ar+1
    or maybe
    Code:
    ++ar
    are called pointer arithmetics. It's very useful when using e.g. linked lists. When travelling through it, you don't need to declare additional integer variables.
    Please excuse my poor english...

  6. #6
    Registered User biosx's Avatar
    Join Date
    Aug 2001
    Posts
    230
    Bravo, Larry! Thank you for pointing that out. Pointer arithmetic is very important in programming C/C++.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. pointers & arrays and realloc!
    By zesty in forum C Programming
    Replies: 14
    Last Post: 01-19-2008, 04:24 PM
  2. Pointers and multi dimensional arrays
    By andrea72 in forum C++ Programming
    Replies: 5
    Last Post: 01-23-2007, 04:49 PM
  3. Passing pointers to arrays of char arrays
    By bobthebullet990 in forum C Programming
    Replies: 5
    Last Post: 03-31-2006, 05:31 AM
  4. pointers
    By InvariantLoop in forum C Programming
    Replies: 13
    Last Post: 02-04-2005, 09:32 AM
  5. Help understanding arrays and pointers
    By James00 in forum C Programming
    Replies: 2
    Last Post: 05-27-2003, 01:41 AM