Thread: Passing int By Reference - I don't get it

  1. #1
    Registered User
    Join Date
    Mar 2012
    Posts
    6

    Passing int By Reference - I don't get it

    The following code yields this compiler warning and it will print, what I think, is a memory address location. I can pass a struct with the same syntax and it works fine. I'm not very good with C, but I enjoy it. Any suggestions as to how I might resolve this?

    w
    arning: format '%d' expects type 'int', but argument 2 has type 'int *'|

    Code:
    #include <stdio.h>
    
    void lax(int *fs);
    
    int main()
    {
    
     int fs = 0;
     lax(&fs);
     return 0;
    
    }
    
    void lax(int *fs) {
            printf("fs: %d\n", fs);  
            return;
    }

  2. #2
    Registered User TheBigH's Avatar
    Join Date
    May 2010
    Location
    Melbourne, Australia
    Posts
    426
    Use %p to print a pointer.
    Code:
    while(!asleep) {
       sheep++;
    }

  3. #3
    Registered User
    Join Date
    Mar 2012
    Posts
    6
    This is the output wuth %d: fs: 2686748
    This is the output wuth %p: fs: 0028FF1C
    Last edited by juuuugroid; 03-27-2012 at 03:42 PM.

  4. #4
    Registered User
    Join Date
    Sep 2007
    Posts
    131
    0028FF1C is hex for 2686748, so you're getting the address either way.

  5. #5
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    You passed a pointer to the function. The name of the pointer is fs.

    If you want to print the value that fs points to, then print *fs, instead of fs.

  6. #6
    Registered User TheBigH's Avatar
    Join Date
    May 2010
    Location
    Melbourne, Australia
    Posts
    426
    Yes, that's right. The first is the address represented as a decimal integer, the second is the same thing in hexadecimal.

    If you want the decimal version but without the compiler warnings you can cast the pointer to an int
    Code:
    printf("fs: %d\n", (int) fs);
    Code:
    while(!asleep) {
       sheep++;
    }

  7. #7
    Registered User
    Join Date
    Mar 2012
    Posts
    6
    Ahh perfect! Thanks much guys. I appreciate. This is an awesome board.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Passing by reference.
    By PaulBlay in forum C++ Programming
    Replies: 5
    Last Post: 06-16-2009, 09:04 AM
  2. passing by reference
    By goran00 in forum C Programming
    Replies: 6
    Last Post: 03-21-2008, 01:03 PM
  3. passing by reference
    By AngKar in forum C Programming
    Replies: 4
    Last Post: 04-27-2006, 09:31 PM
  4. Passing by reference not always the best
    By franziss in forum C++ Programming
    Replies: 3
    Last Post: 10-26-2005, 07:08 PM
  5. passing by address vs passing by reference
    By lambs4 in forum C++ Programming
    Replies: 16
    Last Post: 01-09-2003, 01:25 AM