Thread: pointers when passed as parameters

  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, 02:57 PM
  2. Replies: 6
    Last Post: 07-21-2008, 06:04 AM
  3. Using pointers to pointers
    By steve1_rm in forum C Programming
    Replies: 18
    Last Post: 05-29-2008, 05:59 AM
  4. API "Clean Up" Functions & delete Pointers :: Winsock
    By kuphryn in forum Windows Programming
    Replies: 2
    Last Post: 05-10-2002, 06:53 PM
  5. Pointers, arrays , functions
    By sballew in forum C Programming
    Replies: 19
    Last Post: 09-16-2001, 11:12 PM