pointer and variable scope concept

Discussion in 'C Programming' started by a, Jul 9, 2006.

  1. a

    a Guest

    Hi,
    func(int* p){
    p = p+1;
    }
    main(){
    int* ptr;
    //assume ptr is pointing to a valid allocated array
    func(ptr);
    //Will ptr equal the original address value
    //or equal the original address + sizeof(int)??
    }
    Thanks a lot
    a, Jul 9, 2006
    #1
    1. Advertising

  2. In article <HX8sg.141146$Mn5.44349@pd7tw3no>, a <> wrote:
    >Hi,
    >func(int* p){
    >p = p+1;
    >}
    >main(){
    >int* ptr;
    >//assume ptr is pointing to a valid allocated array
    >func(ptr);
    >//Will ptr equal the original address value
    >//or equal the original address + sizeof(int)??
    >}


    Inside func, p is a *copy* of the value passed in. You then increment
    that copy. The original is not changed.

    If you did wish to permanently increment a pointer from inside a
    function, you would have to pass the -address- of the pointer in,
    and use that address to increment the value stored: that way what
    the function receives is a copy of the address of the pointer, and that
    copy of the address can be used to manipulate what is pointed to
    (i.e., the pointer itself.)
    --
    Is there any thing whereof it may be said, See, this is new? It hath
    been already of old time, which was before us. -- Ecclesiastes
    Walter Roberson, Jul 9, 2006
    #2
    1. Advertising

  3. a

    Chris Dollin Guest

    a wrote:

    > Hi,
    > func(int* p){
    > p = p+1;
    > }


    `p` is a local variable. Changing its value doesn't do anything
    to anything else.

    > main(){
    > int* ptr;
    > //assume ptr is pointing to a valid allocated array
    > func(ptr);
    > //Will ptr equal the original address value


    Yes. The code phrase for this is "C does not have call by reference".

    > //or equal the original address + sizeof(int)??
    > }
    > Thanks a lot


    --
    Chris "C does not have call by name" Dollin
    "Never ask that question!" Ambassador Kosh, /Babylon 5/
    Chris Dollin, Jul 10, 2006
    #3
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Aff@n
    Replies:
    1
    Views:
    362
    Ian Collins
    Oct 16, 2006
  2. gsingh

    pointer concept

    gsingh, Oct 29, 2007, in forum: C Programming
    Replies:
    22
    Views:
    739
    Richard Heathfield
    Oct 30, 2007
  3. Stefan Ram
    Replies:
    5
    Views:
    457
    Mike Schilling
    Apr 15, 2010
  4. David Filmer
    Replies:
    19
    Views:
    240
    Kevin Collins
    May 21, 2004
  5. Andrew Falanga
    Replies:
    2
    Views:
    201
    Andrew Falanga
    Nov 22, 2008
Loading...

Share This Page