Use a pointer to point to the global variable. Change the pointer value. Thats it

Answer from Vamsavardhana Vijay on Stack Overflow
🌐
Reddit
reddit.com › r/c_programming › how do you update a global variable in c?
r/C_Programming on Reddit: How do you update a global variable in c?
September 4, 2016 -

I used to know how to do this, but I've forgotten. I am currently working with a little terminal based game project of mine that requires that global variables be changed so they can be called by multiple functions, and sometimes modified in those functions for later use by one or more functions.

How do you change a global variable?

Edit 2: I solved my problem using pointers. For anyone wondering how to change a global variable (globally), you can use pointers.

Thanks for all the help everyone.

EDIT: Someone asked for the code, so I am including it here. The global variable I need is for the positionx and positiony variables. I am making a little mario type platformer game in terminal and I want to track the position in the 2d space using x and y positions that regularly get updated by different functions.

Right now the problem is the function gravity and the function movement are using two different version of the variables instead of the same one.

I used an array to store the data because I thought I was being clever and that would change the variable globally, but nope it still only does it locally.

Here is the code:


//START OF CODE

include <cs50.h>

include <stdio.h>

include <stdlib.h>

include <unistd.h>

int world[100][119]; int i = 0;
int j = 0;
int k = 0;
int l = 0;
int m = 0;
int n = 0;
int o = 0;
int p = 0;
int q = 0;
int r = 0;
int length = 30;
int height = 119;
int lengthinitialized = 99;
int heightinitialized = 119;
int worldpositionx = 0;
int worldpositiony = 0;
//use an array to track position as it alters a referencable number in a global way
int globalxy[2][2];
//use array to track movements
int movement[1][1];
//win condition has to equal 1 to stop
int won[1][1];

//void draw(void);
void populateboard(void);
void placelimits(void);
void placeobjects(void);
void draw(void);
void initializeplayer(void);
void gravity(void);
void move(void);
void instructions(void);
//void clear(void);

int main(void)
{ won[0][0] = 0;

populateboard();
placelimits();
placeobjects();
initializeplayer();
draw();

while(won[0][0] != 1)
{
    worldpositiony = globalxy[0][1];
    worldpositionx = globalxy[1][0];
    
    if(world[worldpositionx+1][worldpositiony] == 0)
    {
        while(world[worldpositionx+1][worldpositiony] == 0)
        //for(i=0;i&lt;20;i++)
        {
          gravity();
        }
    }
    
    draw();
    instructions();
    move();
    
}

}

void draw(void)
{
//Orignal draw before limited scope
for(m=0;m<length ;m++)
{
if(world[m][n]==0) { printf(" "); } else { printf("%i", world[m][n]); }

    for(n=0;n&lt;height ;n++)
        {
            if(world[m][n]==0)
            {
                printf(" ");
            }
            else
            {
                printf("%i", world[m][n]);
            }
        }
    
    printf("\n");
}

}

// **/

void populateboard(void) { for(i=0;i<lengthinitialized;i++) { for(j=0;j<heightinitialized;j++) { world[i][j] = 0; }

}


/**
 * 0s represent air
 * 1s represent solid objects
 **/

}

void placelimits(void) { //Boundaries are 10 layers thick to accomodate draw distance of 10. for(k=0;l<height; l++) { for(q=0; q<10;q++) { world[q][l] = 1; world[(length -1) - q][l]= 1; } }

for(l=0;k&lt;length;k++)
{
    for(r=0;r&lt;10;r++)
    {
     world[k][(height -1) - r] = 1;
     world[k][r] = 1;
    }
}
/**
 * 0s represent air
 * 1s represent solid objects
 **/

}

void placeobjects(void) { //test object for(o = 1; o<4; o++) { world[(o * 20)][5] = 1;

    world[(o * 20)+1][5] = 1;
    world[(o * 20)-1][5] = 1;
    
    world[(o * 20)][6] = 1;
    world[(o * 20)][4] = 1;
    
}

}

void initializeplayer(void) { world[15][15] = 2; worldpositionx = 15; worldpositiony = 15; globalxy[0][1] = worldpositiony; globalxy[1][0] = worldpositionx;

}

void gravity(void) { //world[worldpositionx][worldpositiony] = 2; worldpositionx = globalxy[0][1]; //redundant line, but for clarity

if(world[worldpositionx+1][worldpositiony] == 0)
{
    worldpositionx = worldpositionx +1;
    globalxy[0][1] = worldpositionx;
    world[worldpositionx][worldpositiony] = 2;
    world[worldpositionx-1][worldpositiony] = 0;
  
    //if position +1 is 0, drop. else end loop
}

}

void move(void)
{
//sideways movement
movement[0][0] = GetInt();
worldpositiony = globalxy[0][1];
worldpositionx = globalxy[1][0];
world[worldpositionx][worldpositiony] = 2;

if((movement[0][0] == 4) &amp;&amp; (world[worldpositionx][worldpositiony-1] == 0))  
{
    worldpositiony = worldpositiony -1; 
    globalxy[0][1] = worldpositiony;
    world[worldpositionx][worldpositiony] = 2;
    world[worldpositionx][worldpositiony+1] = 0;
}
else if((movement[0][0] == 6) &amp;&amp; (world[worldpositionx][worldpositiony+1] == 0))
{
    worldpositiony = worldpositiony +1; 
    globalxy[0][1] = worldpositiony;
    world[worldpositionx][worldpositiony] = 2;
    world[worldpositionx][worldpositiony-1] = 0;
}
else
{
    printf("An error occured \n");
}

//use a variable to track whether to move up down, or sideways. using get int. }

void instructions(void)
{
printf("Press 4 and 6 to move, and press 8 to jump, and press the 7 key to mega jump. Please input your move. \n");
}

/**

  • Clears screen using ANSI escape sequences.

void clear(void) { printf("\033[2J"); printf("\033[%d;%dH", 0, 0); } */

//global variable is not being treated as a global variable. I need to to change it another way. With correct replacement. //pointers seem to be one way to do this. point to the variable that the global variable pulls. and when I want to change it change the value of the things pointed to. //or else find an elegant way to track both of these with local variables. maybe merge movement and gravity so its on the same level.

//END of CODE

If there is better way to show this code, please let me know.

Discussions

Changing a global variable's value with a function with the variable passed as an argument
I’m trying to make a function that can take a global variable as an argument and change the value of the variable globally. I tried: let a = 0 function diffNum(num){ for (let x = 0; x <= 10; x++){ num += x; return num; } · I get 55 back when I input a as an argument, but globally, a is still ... More on forum.freecodecamp.org
🌐 forum.freecodecamp.org
0
0
April 30, 2020
Change value of global variable, C - Stack Overflow
Explore Stack Internal ... Save this question. Show activity on this post. So I'm trying to find a way to update a variable and I've tried to make it global so I can change it easily. The only problem is it isn't working and i don't know how to fix it. I want SIZE_ARRAY to change to the value it becomes every time I call the remove_unimportant_words function... More on stackoverflow.com
🌐 stackoverflow.com
April 20, 2016
How can you modify global variables that are used in functions that are being called with ccall?
From the documentation, I got that it’s possible to retrieve pointers to global variables by using the cglobal function. However, I wasn’t able to figure out from that how I can set the value of a global variable that is being used in a function that I am calling via ccall, or how I can ... More on discourse.julialang.org
🌐 discourse.julialang.org
1
0
December 8, 2024
c++ - Changing global variables in functions - Stack Overflow
I'm learning c++ with the book 'Course beginning c++ through game development'. When i'm declaring a global variable, this global variable is not changable. When im declaring a local variable in a More on stackoverflow.com
🌐 stackoverflow.com
🌐
Quora
quora.com › Is-there-any-way-in-c-to-change-the-value-of-a-global-variable-through-a-function-without-passing-it-to-the-function
Is there any way in c to change the value of a global variable through a function without passing it to the function? - Quora
Answer (1 of 5): A global variable’s value can be changed through a function without passing it as an argument. That’s why they are commonly used in the first place :- See the following :- [code]#include %d\n", c); ...
🌐
IncludeHelp
includehelp.com › code-snippets › c-program-to-define-modify-and-access-a-global-variable.aspx
C program to define, modify and access a global variable
September 20, 2022 - Value will be printed into main() then we are modifying the value of x with 200, printing the value and again modifying the value of x with 300 through the function modify_x() and printing the final value. Here modify_x() is a user defined function that will modify the value of x (global variable), ...
🌐
OnlineGDB
question.onlinegdb.com › 15049 › modify-global-variable-function-continue-value-functions
Can i modify a global variable in a function and continue with that same value in other functions? - OnlineGDB Q&A
You can change the value of a global variable and after the change, everywhere in the code, this new value is stored in the global variable · Your code has many syntax errors, misspelled variable names, and an unusual logic to call the main function from other functions.
🌐
University of Texas
farside.ph.utexas.edu › teaching › 329 › lectures › node19.html
Global variables
When an argument is passed by reference then a local variable in the calling routine shares the same memory location as a local variable in the function which is called: hence, a change in one variable is automatically mirrored in the other. However, there is a third method of transferring information from one function to another. It is possible to define variables which are global in extent: such variables are recognized by all the functions making up the program, and have the same values in all of these functions.
🌐
freeCodeCamp
forum.freecodecamp.org › t › changing-a-global-variables-value-with-a-function-with-the-variable-passed-as-an-argument › 381692
Changing a global variable's value with a function with the variable passed as an argument - The freeCodeCamp Forum
April 30, 2020 - I’m trying to make a function that can take a global variable as an argument and change the value of the variable globally. I tried: let a = 0 function diffNum(num){ for (let x = 0; x <= 10; x++){ num += x; return num; } · I get 55 back when I input a as an argument, but globally, a is still ...
Find elsewhere
🌐
PrepBytes
prepbytes.com › home › c programming › global variable in c
Global Variable in C
1 week ago - A3: Yes, global variables can be modified by any function that has access to them. However, it is essential to be mindful of potential side effects and unintended changes, as global variables can introduce challenges related to code maintainability.
🌐
Scaler
scaler.com › home › topics › what is global variable in c?
What is Global Variable in C? - Scaler Topics
May 21, 2024 - Example 3: Redefining a global variable. ... From the above example, we can observe that C does not allow us to redefine the value of a global variable. When we tried to redefine the global variable, we got a redefinition of 'var' error.
🌐
Quora
quora.com › Can-you-change-a-global-variable-in-a-function
Can you change a global variable in a function? - Quora
C/C++: Global variables declared at file or external scope can be read and written directly from functions. For cross-file access use extern. ... Yes — a function can change a global variable, but behavior and syntax depend on the language ...
🌐
Hero Vired
herovired.com › learning-hub › topics › global-variable-in-c
Global Variable in C Programming: Examples, How to Declare
September 14, 2024 - Here, maxUsers is a constant global variable. It’s available to every function, but its value can’t be changed.
🌐
GeeksforGeeks
geeksforgeeks.org › c language › global-variables-in-c
Global Variables in C - GeeksforGeeks
A global variables are declared outside all functions, usually at the top of the program. Global variables have a program-wide scope which means can be accessed and modified by any function in the program.
Published   2 weeks ago
🌐
BYJUS
byjus.com › gate › global-variable-in-c
Use of the Global Variable in C
3 weeks ago - These do not stay limited to a specific function- which means that one can use any given function to not only access but also modify the global variables. The initialization of these variables occurs automatically to 0 during the time of declaration.
🌐
Cprogramming
cboard.cprogramming.com › cplusplus-programming › 161489-possible-change-value-variable-main-using-function.html
Is it possible to change the value of a variable in main using a function?
Parameters are passed by value in C/C++. What you give to your getValue function is a copy of the value of what was passed in. Within the getValue function itself, changes made to this copy do not affect the content of the original variable you passed in by in main (having them named the same thing doesn't change this aspect BTW).
🌐
Code Quoi
codequoi.com › en › local-global-static-variables-in-c
Local, Global and Static Variables in C - codequoi
January 27, 2023 - Here, the foo function declares ... pointer). Then it can modify the value stored at that address. This is why when main later reads the value of this variable, it will have changed. When we declare a variable outside of any function, it is a global variable....
🌐
TutorialsPoint
tutorialspoint.com › cprogramming › c_scope_rules.htm
C - Scope Rules
June 10, 2022 - A program can have same name for local and global variables but the value of local variable inside a function will take preference.