Thread: pointers/arrays

  1. #1
    Registered User
    Join Date
    Nov 2003
    Posts
    6

    pointers/arrays

    Pointers are passed by reference-- are arrays also passed by reference or are they passed by value?


    thankyou
    ikkin

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    > Pointers are passed by reference
    No, pointers are passed by value, just like everything else in C

    > are arrays also passed by reference
    Not in the C++ sense of reference
    An array decays to a pointer to the first element of the array, and that gets passed by value.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Nov 2003
    Posts
    6
    So in C prog, what is passed by reference?



    -ikkin

  4. #4
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    There isn't, you fake it by passing a pointer to whatever it is you think you need a reference to.

    Eg, in C++ you would do this
    Code:
    void foo ( int &*ptr ) {
        ptr = new int;
    }
    ...
    int *ptr; foo( ptr );
    But in C, you have to do this
    Code:
    void foo ( int **ptr ) {
        *ptr = malloc( sizeof int );
    }
    ...
    int *ptr; foo( &ptr );
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  5. #5
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >So in C prog, what is passed by reference?
    Nothing, C doesn't support pass by reference. It only seems like it does because you can simulate pass by reference through the use of pointers.
    My best code is written with the delete key.

  6. #6
    Registered User
    Join Date
    Nov 2003
    Posts
    6

    Smile

    Thank You!

Popular pages Recent additions subscribe to a feed