Variable scope

This is a discussion on Variable scope within the C Programming forums, part of the General Programming Boards category; I have the following piece of code: Code: int main() { int key = 1; getKey(); printKey(); printf("%s", "Key in ...

  1. #1
    Learner Axel's Avatar
    Join Date
    Aug 2005
    Posts
    335

    Variable scope

    I have the following piece of code:

    Code:
    int main()
    {
       int key = 1;
       getKey();
       printKey();
       printf("%s", "Key in main is: ");
       printf("%d", key);
       return 0;
    }
    
    int getKey()
    {
       int *key;
       printf("Please enter a key: ");
       scanf("%d", &key);
    }
    int printKey()
    {
       int *key;
       printf("%s", "You entered: ");printf("%d\n", key);
    }
    How exactly do i set "key" in main to whatever is being entered in getKey()? I can't use the assign & operator on a pointer so i'm having trouble referencing it.

  2. #2
    cwr
    cwr is offline
    Registered Luser cwr's Avatar
    Join Date
    Jul 2005
    Location
    Sydney, Australia
    Posts
    869
    You could use a pointer:
    Code:
    #include <stdio.h>
    void getKey(int *);
    int main(void)
    {
        int key = 1;
        getKey(&key);
        printf("key = %d\n", key);
        return 0;
    }
    
    void getKey(int *k)
    {
        printf("Please enter a key: ");
        fflush(stdout);
        scanf("%d", k);
    }
    Or you could return a value:
    Code:
    #include <stdio.h>
    int getKey(void);
    int main(void)
    {
        int key = 1;
        key = getKey();
        printf("key = %d\n", key);
        return 0;
    }
    
    int getKey(void)
    {
        int k;
        printf("Please enter a key: ");
        fflush(stdout);
        scanf("%d", &k);
        return k;
    }

  3. #3
    ---
    Join Date
    May 2004
    Posts
    1,379
    Find a tutorial on function paramters and pointers
    Code:
    #include <stdio.h>
    
    void getKey(int *key){
       printf("Please enter a key: ");
       scanf("%d", key);
    }
    
    void printKey(int *key){
       printf("You entered: ");
       printf("%d\n", *key);}
    
    int main(void){
       int key = 1;
       getKey(&key);
       printKey(&key);
       printf("Key in main is: ");
       printf("%d", key);
       return 0;
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. making a wstring variable global scope
    By stanlvw in forum C++ Programming
    Replies: 1
    Last Post: 07-12-2008, 03:25 PM
  2. Need some help...
    By darkconvoy in forum C Programming
    Replies: 32
    Last Post: 04-29-2008, 04:33 PM
  3. Post...
    By maxorator in forum C++ Programming
    Replies: 12
    Last Post: 10-11-2005, 09:39 AM
  4. variable in file scope ???
    By howhy in forum C++ Programming
    Replies: 5
    Last Post: 08-30-2005, 05:46 AM

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