pointers when passed as parameters

This is a discussion on pointers when passed as parameters within the Linux Programming forums, part of the Platform Specific Boards category; I've been wondering: what happens to a pointer when it's passed as a parameter to a function? Why is this: ...

  1. #1
    Registered User
    Join Date
    Jul 2002
    Posts
    29

    pointers when passed as parameters

    I've been wondering: what happens to a pointer when it's passed as a parameter to a function? Why is this:

    <code>

    int main(void) {

    char *str;
    *str = 'a';

    return 0;

    </code>

    not legal, while this is perfectly legal:

    <code>

    void function(char *);

    void function(char *str) {

    *str = 'a';

    }

    int main(void) {

    char *str;

    function(str);

    return 0;

    }

    </code>

    Thanks
    Skarr
    I like traffic lights. I like traffic lights. I like traffic lights, but only when they're green.

  2. #2
    Registered User
    Join Date
    Jul 2002
    Posts
    29

    Well, yeah

    I know that, but if I initialize the string in main() I would have a locked size for my string. And if i read stuff from (say) a file, I won't know how big tje buffer should be.
    I like traffic lights. I like traffic lights. I like traffic lights, but only when they're green.

  3. #3
    Registered User
    Join Date
    Aug 2002
    Location
    Hermosa Beach, CA
    Posts
    446
    I don't think it's a good idea either way. Your char* points to garbage, so you need to point it to an actual buffer:

    Code:
    void funct(char* buffer, int size)
    {
       /* do whatever operation you want on up to size
            bytes of the buffer */
    }
    
    int main()
    {
        /* obviously you must define MAX_BUFFER_SIZE to 
            something approprate somewhere */
        char buffer[MAX_BUFFER_SIZE];
        char* pbuffer = buffer;
    
        /* of course you could just pass buffer too */
        funct(pbuffer, MAX_BUFFER_SIZE);
    
        return 0;
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Hey guys..need help on pointers
    By Darkozuma in forum C++ Programming
    Replies: 5
    Last Post: 07-25-2008, 03:57 PM
  2. Replies: 6
    Last Post: 07-21-2008, 07:04 AM
  3. Using pointers to pointers
    By steve1_rm in forum C Programming
    Replies: 18
    Last Post: 05-29-2008, 06:59 AM
  4. API "Clean Up" Functions & delete Pointers :: Winsock
    By kuphryn in forum Windows Programming
    Replies: 2
    Last Post: 05-10-2002, 07:53 PM
  5. Pointers, arrays , functions
    By sballew in forum C Programming
    Replies: 19
    Last Post: 09-17-2001, 12:12 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21