problem with passsing array to a function

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Hasan Kayani
    New Member
    • Mar 2012
    • 1

    problem with passsing array to a function

    Hi

    I have an array defined as
    double temp[5] = {0,0,0,0,0};

    and a function
    double function(double *something);

    i am trying to do
    double x = function(temp);

    but this only passes the first element of the array and not the complete array to the function. How can I correct this?
    Thank you.
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    The name of an array, temp in this case, is always the address of element 0. So temp is really a double* containing he address of
    temp[0].

    That means your function doesn't know how many elements are in the array unless you have a second argument with that information.

    Next, you cannot return an array from a function. The rules on returns say you can return a type or a pointer to a type. An array doesn't fit this because you also need the number of elements.

    You might read: http://bytes.com/topic/c/insights/77...rrays-revealed

    Comment

    • BarkhaDhamechai
      New Member
      • Mar 2012
      • 1

      #3
      The pointer in the function stores the base address,i.e,in this case temp[0].
      To access the other elements you can use an offset i(say) and access the array as *(something+i).
      Also you cannot return array from function and since you are passing the array by reference there is no need of doing this. after the main once the control passes to main() the array modifications done in the function will remain as the address of the array was passed.

      Comment

      • weaknessforcats
        Recognized Expert Expert
        • Mar 2007
        • 9214

        #4
        You cannot use *(something+i) because you don't know the size of the array. If you do this and access memory outside he array you will crash the program on a segmentation fault.

        Also, arrays are not passed by reference. All that's passed is the address of element 0 and that is passed by value since the pointer something is not the same pointer as temp. There is no pass by reference in C.

        Comment

        Working...