Thread: Use pointers instead of global variables?

  1. #1
    Registered User
    Join Date
    Oct 2014
    Posts
    9

    Use pointers instead of global variables?

    I have made an application and I have basically solved everything. But the only problem is that I am using global variables because it felt like the smoothest, so my program is built on it.

    But now I've read around and I understand that you should not use these(?). Do you think pointers is the best think to use instead?
    I have previously declared my board array and some variables as global and I want them in alot of functions.

    I have read and understand the procedure for the use of pointers so I can use my int's in the other functions by doing like this?
    Code:
    #include <stdio.h>
    
    int justprint();
    
    
    int main()
    {
        int Row = 2;
        int Column = 2;
        int *pRow = &Row;
        int *pColumn = &Column;
        
        justprint(&pRow, &pColumn);
        
        return 0;
    }
    
    
    int justprint(int **pRow, int **pColumn)
    {
        
       
       
        printf("\n\n\n Row: %d \n", **pRow);
        printf("\n\n\n Column: %d \n", **pColumn);
    
    
    }


    But how do I do it with an array like this one? If I declare it in the main function, and then want to use it in other functions. How do I do then? Or are there better, easier solutions?
    Code:
    char game[3][3]={{0,0}};
    Regards

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by smaugz
    But now I've read around and I understand that you should not use these(?).
    Yes, you should avoid the use of global variables. They tend to make it harder for you to reason about your program. They also make it harder for you to reuse functions.

    Quote Originally Posted by smaugz
    Do you think pointers is the best think to use instead?
    It depends on the situation. If you want to pass an object to a function such that it will be modified in the function and the result will be reflected in the caller, then you might pass a pointer to it. Or, perhaps the object is expensive to copy, so you pass a pointer to it because pointers are relatively cheap to copy. Or, you might be passing an array to a function, and since an array will be converted to a pointer to its first element, you end up passing a pointer instead.

    Quote Originally Posted by smaugz
    I have read and understand the procedure for the use of pointers so I can use my int's in the other functions by doing like this?
    This is sloppy:
    Code:
    int justprint();
    It declares a function named justprint that returns an int and takes an unknown number of arguments. This means that the compiler will not check that the calls of this function match the actual function signature. Rather, declare it as:
    Code:
    int justprint(int **pRow, int **pColumn);
    Actually, the return type of justprint should be void since you do not return a value. Furthermore, it was not necessary to have pointer parameters since you are only passing ints and not modifying them from within the function.

    Quote Originally Posted by smaugz
    But how do I do it with an array like this one? If I declare it in the main function, and then want to use it in other functions. How do I do then? Or are there better, easier solutions?
    In most contexts, an array is converted to a pointer to its first element. So, with an array like this:
    Code:
    char game[3][3] = {{0}};
    You end up with a pointer to an array of 3 chars. Therefore, you can declare your function as:
    Code:
    void justprint(char (*game)[3]);
    In the definition of justprint, you can access game[i][j] as per normal array notation.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    Oct 2014
    Posts
    9
    Thanks for a really nice and quick answer laserlight!

    Quote Originally Posted by laserlight View Post
    Yes, you should avoid the use of global variables. They tend to make it harder for you to reason about your program. They also make it harder for you to reuse functions.
    Allright! Then I understand.

    Quote Originally Posted by laserlight View Post
    It depends on the situation. If you want to pass an object to a function such that it will be modified in the function and the result will be reflected in the caller, then you might pass a pointer to it. Or, perhaps the object is expensive to copy, so you pass a pointer to it because pointers are relatively cheap to copy. Or, you might be passing an array to a function, and since an array will be converted to a pointer to its first element, you end up passing a pointer instead.
    That is exactly what I want in this case.

    Quote Originally Posted by laserlight View Post
    In most contexts, an array is converted to a pointer to its first element. So, with an array like this:
    Code:
    char game[3][3] = {{0}};
    You end up with a pointer to an array of 3 chars. Therefore, you can declare your function as:
    Code:
    void justprint(char (*game)[3]);
    In the definition of justprint, you can access game[i][j] as per normal array notation.
    Hmm, I dont really understand what you mean here. But I think I get some of it.

    I just made that code as an example. Im about to make a tictactoe-game right now. If you have time it would be nice if you could check my code and tell me if you have any other nice idéa how to fix the problem with the global variables.

    My code so far: (Havnt done the winner function yet )
    Code:
    /*     Tic Tac Toe av Rickard Carlsson
        Spelet går ut på att man skall få tre i rad. 
        Antingen vågrätt, lodrätt eller diagonalt. */
    
    #include <stdio.h>
    #include <stdlib.h>
    #include <math.h>
    #include <time.h>
    
    #define NUMBER_TO_WIN  3
    #define PLAYER 'X'
    #define BOT 'O'
    
    //  -----------------------------------------
    //  Functions-initiering.
    //  -----------------------------------------
    void drawBoard();
    int playerChoise();
    int botChoise();
    
    //  -----------------------------------------
    // Global variables
    //  -----------------------------------------
    char game[3][3]={{0,0}};
    int totalEntry =0,Row,Column;
    
    //  -----------------------------------------
    //  Main-functionen
    //  -----------------------------------------
    int main()
    {
        printf("Welcome to Tic Tac Toe!\n");
        printf("What the board looks like:\n\n");
        drawBoard(game);
    
        while(totalEntry<=9)
        {
             playerChoise();
             botChoise();
             drawBoard(game);
        }          
    
        printf("The game is over.");
        getchar();
        return 0;
    }
    
    
    
    //  -----------------------------------------
    //  The function where the board draws.
    //  -----------------------------------------
    void drawBoard(char game[][3])
    {
        for ( Row = 0 ; Row < 3 ; Row++ )
        {
            for ( Column = 0 ; Column < 3 ; Column++ )
            {
                if(game[Row][Column])
                {
                   printf( "|%c", game[Row][Column] );
                }
                else
                {
                    printf("| ");                         
                }
            }
            printf("|\n");
        }
    }
    
    //  -----------------------------------------
    //  The function where the bot makes its choise.
    //  -----------------------------------------
    int botChoise()
    {
        // Just a random number so that the loop never will stop until it breaks.
        while (BOT != 3000)
        {
            Row = rand()%3;
            Column = rand()%3;
            // The loop breaks when the spot is empty. Then I want to write 'O' into that spot.
            if (game[Row][Column] == 0 )
            {
                break;
            }
        }
        //BOT is defined to the letter 'O'
        game[Row][Column] = BOT;
        totalEntry++;
        return game;
    }
    
    //  -----------------------------------------
    //  Function where I choose a spot on the board. 
    //  -----------------------------------------
    int playerChoise(void)
    {
        // Just a random number so that the loop never will stop until it breaks.
        while ( PLAYER != 3000 )
        {
            printf("\nEnter row-number of your choise(1-3):\n");
            scanf("%d", &Row);
            printf("Enter column-number of your choise(1-3):\n");
            scanf("%d", &Column);
            Row = Row-1;
            Column = Column-1;
            
            if (game[Row][Column] == 0 )
            {
                break;
            }
            else 
            {
                printf("That spot is taken. Try another one:\n");
            }
        }
        
        game[Row][Column] = PLAYER;
        totalEntry++;
        return game;
    }

  4. #4
    Registered User
    Join Date
    Jun 2011
    Posts
    4,513
    You can get rid of the global variables by declaring them in the functions they're needed, and passing them to other functions that also need them.

    Code:
    // Just a random number so that the loop never will stop until it breaks.
    While not actually wrong, it's more normal to write an infinite loop as simply:

    Code:
    while(1)
    Warnings from the compiler:

    Code:
    /*
    main.c||In function 'botChoise':|
    main.c|91|warning: return makes integer from pointer without a cast|
    main.c||In function 'playerChoise':|
    main.c|121|warning: return makes integer from pointer without a cast|
    ||=== Build finished: 0 errors, 2 warnings ===|
    */
    You can't return an array from a function. You don't even have to - just update it in the function as you're doing.

    I'd recommend doing a search for "c programming passing 2d array to function". Create a new simple program just for practicing, before trying to apply it to your current code.

  5. #5
    Registered User
    Join Date
    Oct 2014
    Posts
    9
    Quote Originally Posted by Matticus View Post
    You can get rid of the global variables by declaring them in the functions they're needed, and passing them to other functions that also need them.
    Allright! But how can I then set the value to 0 on all spots on the board? Should I just declare it with value 0 in the main and skip that in the functions then?

    Quote Originally Posted by Matticus View Post
    While not actually wrong, it's more normal to write an infinite loop as simply:

    while(1)
    Thanks for the tip. I didnt know you could do that!

    Quote Originally Posted by Matticus View Post
    Warnings from the compiler:

    *Warnings*

    You can't return an array from a function. You don't even have to - just update it in the function as you're doing.
    Thanks! I just fixed that!

    Quote Originally Posted by Matticus View Post
    I'd recommend doing a search for "c programming passing 2d array to function". Create a new simple program just for practicing, before trying to apply it to your current code.
    Will try. Thank you very much for your answer!

  6. #6
    Registered User
    Join Date
    Jun 2011
    Posts
    4,513
    Allright! But how can I then set the value to 0 on all spots on the board? Should I just declare it with value 0 in the main and skip that in the functions then?
    If you're talking about initializing all elements to zero, then yes. Declare the array in "main()" and set it to all zeroes. This can be as simple as:

    Code:
    char game[3][3]={{ 0 }};
    An array declared in a function (such as "main()") is not automatically initialized to anything. The example above initializes all elements to zero.

    This is because the standard states that if only some of the elements of an array are initialized, then the rest will automatically be initialized to zero. So by setting the first element to zero as in the example I gave, all other elements will be set to zero.

  7. #7
    Registered User
    Join Date
    Oct 2014
    Posts
    9
    Quote Originally Posted by Matticus View Post
    *TEXT*
    Thanks! I see!

    I have done that now. Now the program register the bots&my choise but it doesnt display. I think that it might be problem with the functions and has something to do with that I have void in the paranthesis "()" or what can the problem be? Sorry for asking tons of probably stupid questions but Im so glad that you experts can help a n00b like me! I really appretiate your help.


    Code:
    /* Info: */
    
    #include <stdio.h>
    #include <stdlib.h>
    #include <math.h>
    #include <time.h>
    
    #define NUMBER_TO_WIN  3
    #define PLAYER 'X'
    #define BOT 'O'
    
    //  -----------------------------------------
    //  Functions-initiering.
    //  -----------------------------------------
    void drawBoard();
    int playerChoise();
    int botChoise();
    
    //  -----------------------------------------
    // Global variables
    //  -----------------------------------------
    //char game[3][3]={{0}};
    //int totalEntry =0,Row,Column;
    
    //  -----------------------------------------
    //  Main-functionen
    //  -----------------------------------------
    int main()
    {
        char game[3][3]={{0}};
        int totalEntry=0;
        printf("Welcome to Tic Tac Toe!\n");
        printf("What the board looks like:\n\n");
        drawBoard(game);
    
        while(totalEntry<=9)
        {
             playerChoise();
             botChoise();
             drawBoard(game);
        }          
    
        printf("The game is over.");
        getchar();
        return 0;
    }
    
    
    
    //  -----------------------------------------
    //  The function where the board draws.
    //  -----------------------------------------
    void drawBoard(char game[3][3])
    {
        int Row,Column;
        for ( Row = 0 ; Row < 3 ; Row++ )
        {
            for ( Column = 0 ; Column < 3 ; Column++ )
            {
                if(game[Row][Column] != 0)
                {
                   printf( "|%c", game[Row][Column] );
                }
                else
                {
                    printf("| ");                         
                }
            }
            printf("|\n");
        }
        
    }
    
    //  -----------------------------------------
    //  The function where the bot makes its choise.
    //  -----------------------------------------
    int botChoise()
    {
        char game[3][3];
        int Row,Column,totalEntry;
        
        // Infinite-loop
        while (1)
        {
            Row = rand()%3;
            Column = rand()%3;
            // The loop breaks when the spot is empty. Then I want to write 'O' into that spot.
            if (game[Row][Column] == 0 )
            {
                break;
            }
        }
        //BOT is defined to the letter 'O'
        game[Row][Column] = BOT;
        totalEntry++;
        return 0;
    }
    
    //  -----------------------------------------
    //  Function where I choose a spot on the board. 
    //  -----------------------------------------
    int playerChoise(void)
    {
        char game[3][3];
        int Row,Column,totalEntry;
        // Infinite-loop
        while (1)
        {
            printf("\nEnter row-number of your choise(1-3):\n");
            scanf("%d", &Row);
            printf("Enter column-number of your choise(1-3):\n");
            scanf("%d", &Column);
            Row = Row-1;
            Column = Column-1;
            
            if (game[Row][Column] == 0 )
            {
                break;
            }
            else 
            {
                printf("That spot is taken. Try another one:\n");
            }
        }
        
        game[Row][Column] = PLAYER;
        totalEntry++;
        return 0;
    }

  8. #8
    Registered User MutantJohn's Avatar
    Join Date
    Feb 2013
    Posts
    2,665
    Are you declaring game twice?

  9. #9
    Registered User
    Join Date
    Oct 2014
    Posts
    9
    Quote Originally Posted by MutantJohn View Post
    Are you declaring game twice?
    Naa, I decalared it as a global variable first but that row of code is just a comment. "//" Or where do you mean?

  10. #10
    Registered User MutantJohn's Avatar
    Join Date
    Feb 2013
    Posts
    2,665
    Oh my bad, did not see that it was a comment lol.

  11. #11
    Citizen of Awesometown the_jackass's Avatar
    Join Date
    Oct 2014
    Location
    Awesometown
    Posts
    269
    the totalEntry in the other routines is completely different from the totalEntry in main.
    add this line in the main loop:
    Code:
     totalEntry+=2
    Same applies to the game[][] defined in each function. You've got to pass the game[][] defined in main to the other routines.
    Last edited by the_jackass; 10-18-2014 at 04:02 AM.

  12. #12
    Registered User
    Join Date
    Oct 2014
    Posts
    9
    Quote Originally Posted by the_jackass View Post
    the totalEntry in the other routines is completely different from the totalEntry in main.
    add this line in the main loop:
    Code:
     totalEntry+=2
    Same applies to the game[][] defined in each function. You've got to pass the game[][] defined in main to the other routines.
    Thanks!

    How do I do that?

  13. #13
    Registered User
    Join Date
    Oct 2014
    Posts
    9
    The problem for me now is that the program get mine and the bots choises but doesnt print them out. And I understand that the problem is in the drawBoard function. The variables Row and Column is local there and cant connect to the values from the other functions. How do I fix that? I understand how pointers work in easy examples but I cant really understand how I should use them here. Any thoughts? =)

    I really appreciate any help you can provide.

  14. #14
    Registered User
    Join Date
    Oct 2014
    Posts
    9
    Nevermind! I fixed it. Thanks for help everyone

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 43
    Last Post: 05-23-2013, 03:01 PM
  2. Global Access to Global Class without so many pointers
    By parad0x13 in forum C++ Programming
    Replies: 1
    Last Post: 11-11-2009, 02:48 PM
  3. static global & global variables
    By aqeel in forum C Programming
    Replies: 1
    Last Post: 09-25-2009, 12:32 PM
  4. Use global variables or pointers?
    By RealityFusion in forum C++ Programming
    Replies: 5
    Last Post: 09-22-2005, 08:47 PM
  5. non global variables
    By algi in forum C++ Programming
    Replies: 1
    Last Post: 01-10-2005, 01:02 PM

Tags for this Thread