Global variable as an argument of function call in C [closed] - c

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
"While passing global variable in function parameter, is it passed by reference or value ?"

It is passed by value. The following code shows that this is the case:
#include <stdio.h>
int global = 5;
void foo(int bar){
bar = 6;
printf("bar = %d\nglobal = %d", bar, global);
}
int main(){
foo(global);
return 0;
}
The output is:
bar = 6
global = 5
In this code global was passed as a parameter for foo, we called this parameter bar. So at the beginning global and bar are two different variables both having the value 5. But then bar is assigned the value 6 and since the argument was referenced by value, global stays at 5.
To pass the variable by reference, use pointers:
#include <stdio.h>
int global = 5;
void foo(int *bar){
*bar = 6;
printf("bar = %d\nglobal = %d", *bar, global);
}
int main(){
foo(&global);
return 0;
}
Now the output is:
bar = 6
global = 6

Both local and global variables are passed to functions by value in C. If you need to pass by reference, you will need to use pointers.

How the variable is/must be passed, depends on the function, not on the variable:
int gMyVar;
void foo(int a); // says "call me by value"
void bar(int *b); // says "call my by reference"
foo requires an int to be passed. you must call it as foo(gMyVar).
bar requires a pointer to an int. You must call it as bar(&gMyVar).
So, as other answers indicated, C always passes a value, however, the value can be the value of a variable (call by value) or can be a pointer to a variable (call by reference).

First of all, Why do we need to pass Global variable in a function? we can directly access it any where in the program if you dont know.
#include <stdio.h>
int x = 10; //global variable
void fun()
{
printf("%d",x); // direct access
}
int main(void) {
fun(); // no argument required
return 0;
}
Output
10
For demo http://ideone.com/VLWqNO

Related

C how to check if a memory address is still in scope [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I wonder that is it possible to check if a variable is still in scope in c or if a pointer points to a variable that is out of scope. What I ultimately want to do is check the pointers that and if they point to a variable that is out of scope then drop the pointer by calling free. so if you guys could help me I would be more than happy. thank you all for you contrubutions.
EDIT:
You could also skip the structure part and just set the pointer to NULL with macros and then check if it's NULL with a macro;
void some_function(int* input)
{
if (CHECK_POINTER(input))
{
*input = 50;
}
};
int main()
{
int* point ;
CLEAR_POINTER(point);
int a=-1;
some_function(point);
printf("%d\n", a);
ASSIGN_POINTER(point, &a);
some_function(point);
printf("%d\n", a);
}
OLD:
If you are trying to keep track if the pointer is assigned to a certain variable, you could use a structure that contains the pointer variable itself and a variable that is either 0 or 1 when the pointer has been assigned to certain variable.
You can then use macros to assign pointer, clear pointer or check if pointer is assigned a variable address;
#include <stdio.h>
#define DEFINE_POINTER_DATA_STRUCTURE(data_type)\
typedef struct \
{ \
int is_assigned; \
data_type *pointer; \
}PDS_##data_type;
#define POINTER_DATA_STRUCTURE(data_type) PDS_##data_type
// The above allows you to have custom types
DEFINE_POINTER_DATA_STRUCTURE(int) // Define a struct of int pointer
#define ASSIGN_POINTER(structure, address) structure.pointer = address; structure.is_assigned = 1;
#define CLEAR_POINTER(structure) structure.pointer = 0x00; structure.is_assigned = 0;
#define CHECK_POINTER(structure) structure.is_assigned
#define GET_POINTER(structure) structure.pointer
void some_function(POINTER_DATA_STRUCTURE(int) input)
{
if (CHECK_POINTER(input))
{
*GET_POINTER(input) = 50;
}
};
int main()
{
POINTER_DATA_STRUCTURE(int) pointer_structure;
CLEAR_POINTER(pointer_structure);
int a=-1;
some_function(pointer_structure);
printf("%d\n", a);
ASSIGN_POINTER(pointer_structure, &a);
some_function(pointer_structure);
printf("%d\n", a);
}

C, pass by value, in Linux [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I have a function as follows:
void foo (int *check){
*check= 9;
printf("*check: %d\n",*check);
//when I print "*check" here, the value changes as 9.
}
This is the main function.
void main () {
int check=5;
foo(&check);
printf("check: %d\n",check);
//when I print "check", gives me 5.
}
I want to change the value of "check" variable but it does not work. Where am I making mistake? Thank you!
I am using makefile while running it.
Edit: malloc is deleted now it gives me Segmentation fault (core dumped) error
When you malloc within foo, the dereference now points to the value malloced within the function's scope. This means that the value within the function is changed and not the value outside of the function. To correct this, you don't need to malloc within the function to change the value of check:
void foo (int *check) {
*check= 9;
}
void main () {
int check = 5;
foo(&check); // check is now 9
}
You are doing everything just fine, the only thing that is wrong is trying to malloc the variable you passed to the function , since it is already allocated on stack. In order to do what you're trying to do, you should declare the integer as pointer to integer (int *check) outside the function, and avoid using the & character when calling the function with the pointer as parameter.
To change a variable through a function you need to pass it by reference, not value. Your title and code do not match.
Here is a version with both kinds of arguments, side by side:
#include <stdio.h>
int foo(int *ref, int val) {
*ref = 1122; // by reference
val = 1155; // by value
printf("inside:\n%d %d\n", *ref, val);
return val; // otherwise "val=1155" is lost
}
int main(void) {
int ree = 12; // "referencee"
int v = 15;
printf("main:\n%d\n", foo(&ree, v)); // return value (1155)
printf("%d %d\n", ree, v); // 1122 and 15
}
ree is passed as &ree to ref; this address/pointer gets dereferenced inside the function with *ref to change ree's value.
You passed the variable check to the function foo by reference through a pointer to it
int check=5;
foo(&check);
So dereferencing the pointer you could get a direct access to the variable check and could change it like
*check= 9;
However within the function you reassigned the pointer with a new address of a dynamically allocated memory
check= malloc(sizeof(int));
So now the pointer check doe not point to the original object passed to the function by reference. As a result this statement
*check= 9;
changes the dynamically allocated object of the type int instead of changing the variable passed to the function by reference.
Edit: malloc is deleted now it gives me Segmentation fault (core
dumped) error
It is a bad idea to change such dramatically the code in the question because it will only confuse readers of the question and answers. Neither segmentation fault should occur. It seems the new provided code in the question does not correspond to the actual code that generates a segmentation fault.
Here is a demonstrative program. It compiles and runs successfully.
#include <stdio.h>
void foo ( int *check )
{
*check = 9;
printf( "Inside foo check = %d\n", *check );
}
int main(void)
{
int check = 5;
printf( "Before foo check = %d\n", check );
foo( &check );
printf( "After foo check = %d\n", check );
return 0;
}
The program output is
Before foo check = 5
Inside foo check = 9
After foo check = 9

How to pass function pointer to function in c? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
Can anybody please guide me how to pass a function pointer to a function as argument one with second argument being int*? The function then calls a function whose pointer is passed as first argument by passing the
second argument to it.
I Can give you this example
int plus_one(int nb)
{
return nb + 1;
}
int call_func(int (*func)(int), int *param)
{
return (*func)((*param));
}
I Think what you want is the call_func functions, so the important is to pass as first paramaeter something with this format :
return_type (*name_you_give_to_the_function)(parameter_type1, parameter_type2, ...) //parentheses to indicates that is a function
So with that you can make function calling any type of function
to call your call function , just write the name of your function as first parameter :
Exemple link to the previous one
int main(void)
{
int nb = 3;
int res = call_func(plus_one, &nb);
printf("res: %d\n", res);
}
A function with an int * parameter is declared as void FunctionName(int *). (You can use something other than void for the return type.)
Then a pointer to such a function is declared as void (*PointerName)(int *).
So to declare a function with a parameter of this type, we use that declaration for the parameter: void CallingFunctionName(void (*PointerName)(int *), int *IntegerName).
Here is an example:
void CallingFunction(void (*PointerToFunction)(int *), int *Q)
{
PointerToFunction(Q); // Call the function and pass it Q.
}
Notes
Note that to call a function by a pointer, you just have to write a function call using the pointer, PointerToFunction(Q). You do not have to use * to make the pointer into a function, as in (*PointerToFunction)(Q). All function calls are actually done through pointers, and, when you use a function name in a function call, it is automatically converted to a pointer anyway. So, when you already have a pointer, just use it.
Similarly, because you can only pass a pointer to a function as a parameter, not an actual function, if you use a function declaration for a parameter, it will be automatically adjusted to be a pointer to a function. This means we can change the example to:
void CallingFunction(void PointerToFunction(int *), int *Q)
{
PointerToFunction(Q);
}

How to pass local int variables as parameters to a function? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am having problem with the bolded variables. CLion said that those parameters are never accessed.
When I call the function open_turn, the turn_face, and turn_suit are said that they have not been initialized. But I do not want to initialize those variables by assigning values to them since the values are only determined after the function is called.
How do I pass int turn_card, int turn_f, and int turn_s into the function open_turn? Then assigning value of int turn_card to int turn, int turn_f to int turn_face, and int turn_s to turn_suit?
P/s: At this moment, parameters int turn_f and int turn_s are said to be declared but never accessed.
void open_turn(int current_deck[], int turn_card, int turn_f, int turn_s);
int main() {
int turn;
int turn_face;
int turn_suit;
open_turn(deck, turn, turn_face, turn_suit);
}
void open_turn(int current_deck[], int turn_card, int turn_f, int turn_s) {
turn_card = current_deck[card_idx++];
turn_f = turn_card%13;
turn_s = turn_card/13;
You're doing this all wrong. In c, when you pass an argument to a function, you end up passing a copy of the the variable by value. Modifying the variable in the function has no (useful) impact, since you're just modifying a temporary copy of the variable which is discarded when the function call finishes. The compiler is right to barf out errors for this. To accomplish what you likely intend to do, you need to use pointers, and you still need to initialize them.
Note that you likely still have errors in your code since you haven't shown us how current_deck is defined.
Code Listing
/*******************************************************************************
* Preprocessor directives.
******************************************************************************/
#include <stdio.h>
/*******************************************************************************
* Function prototypes.
******************************************************************************/
void open_turn(int current_deck[], int turn_card, int turn_f, int turn_s);
/*******************************************************************************
* Function definitions.
******************************************************************************/
int main(void)
{
int turn;
int turn_face;
int turn_suit;
open_turn(deck, &turn, &turn_face, &turn_suit);
/* The following also works. */
int* pTurn = &turn;
int* pTurn_face = &turn_face;
int* pTurn_suit = & turn_suit;
open_turn(deck, pTurn, pTurn_face, pTurn_suit);
}
void open_turn(int current_deck[], int* turn_card, int* turn_f, int* turn_s)
{
if ( !turn_card || !turn_f || !turn_s )
{
printf("Invalid input.\n");
return;
}
*turn_card = current_deck[card_idx++];
*turn_f = turn_card%13;
*turn_s = turn_card/13;
}
If you want to return back a value from a function in C you must pass a pointer to the variable. For example:
#include <stdio.h>
void f( int x, int *p) {
x = 0; /* This only affects local param x */
*p = 5; /* copies x's value into variable pointed to by p */
}
int main() {
int a = 1, b = 2;
f(a, &b); /* a passed by value, b's address is passed */
printf("a = %d, b= %d\n", a, b); /* prints out a = 1, b = 5 */
}
Here the compiler might warn that the x variable in function f is assigned a value that is not accessed, since setting it to 0 had no affect on a in main. *p = 5 did not create a warning because it is affecting b's value which is then used in the printf call.

How to update a variable using a function with no arguments and no return type in C

I know that If a function has no argument & only return type (say int), then I can change my int variable by assigning the function to my variable as below,
main()
{
int var_name;
var_name = func();
printf("My variable value is updated as : %d", a);
}
func()
{ return 100; }
Also I know that If I have my function's return type as void, with no arguments, then I can only print the value inside the function itself and cannot return anything in turn.
But, my doubt is, is there anything else that I can do to update my var_name by calling a function with no arguments & no return type ?
ie., void func(void); by using something like pointer concepts ??
I could not able to find the exact answer for the same by my searches among so many websites.. I will be very grateful if someone can help me out finding whether I can do it by this way or not,.
Thanks,.
It is possible to modify a local variable in main, from a function with no arguments and no return value, if there's a global pointer to it:
#include <stdio.h>
int *p;
void func() {
*p = 6;
}
int main() {
int a = 5;
p = &a;
func();
printf("a = %d\n", a); // prints: a = 6
return 0;
}
There's no good way to do that. If you want the function to modify a local variable, you should probably change the function so it either returns a value that you can assign to the variable, or takes the variable's address as an argument.
But if you don't mind writing some ugly code, you can define a global (file-scope) pointer variable, assign the local variable's address to the global pointer, and then use that to modify the variable inside the function.
An example:
#include <stdio.h>
int *global_pointer;
void func(void) {
*global_pointer = 42;
}
int main(void) {
int local_variable = 0;
global_pointer = &local_variable;
func();
printf("local_variable = %d\n", local_variable);
}
It's very easy to shoot yourself in the foot his way. For example, if you refer to the pointer after the calling function has terminated (and the local variable no longer exists), you'll have undefined behavior.
This technique can actually be useful if you need to make a quick temporary change in a body of code in which you can't make major interface changes. Just don't do it in code that will be maintained by anyone else -- and wash your hands afterward.
You can have global variable
int var_name;
void func();
int main()
{
func();
printf("%d\n",var_name);
}
void func()
{
var_name = 20;
}
But if your variable is local to main() then this can't be done.
There are two ways to modify the value of var_name.
Make changes in the calling function and return the value.( which you have already shown)
Pass the address of the var_name to the function and have pointer as arguement in the func(int *p) and modify the value inside the func()
Thats it!! No other way this can be done.

Resources