This is a simple test program where I am trying to get the func function to modify the variables a and b which are then used in the main function. Is there a way to get func to return the modified variables so they can be used? (preferably without using struct as I don't understand how it works)
#include <stdio.h>
void func(int a, int b)
{
a=a+1;
b=b+1;
}
void main(void)
{
int a=0, b=0;
while (1)
{
func(a,b);
printf("%d\n",a);
}
}
If you want to modify variables in the calling function, you have to pass their address to func (i.e. pass a pointer to these variables
void func(int* a, int* b)
{
*a=*a+1;
*b=*b+1;
}
func(&a,&b);
Your code passes its arguments by value. This means that a and b are copied into new variables which are initialised with the values of the calling variables but only exist for the duration of func.
I agree. The best way to do this is using pointers. But are you aware that your code will never terminate? You should use a condition that can end excution of the while loop.
Also, if you wanna perfom the exact same action to both variables you could just use the return statement like this:
#include <stdio.h>
void func(int a, int b)
{
return a+1;
}
void main(void)
{
int a=0, b=0;
while (a < 5)
{
func(a);
func(b);
printf("%d\n",a);
}
}
We can achieve through pointers . Don't use While(1) because it will go to infinite loop. I think following program help to you.
#include <stdio.h>
void func(int* a, int* b)
{
*a=*a+1;
*b=*b+1;
}
void main(void)
{
int a=0, b=0;
//while (1)
// {
func(&a,&b);
printf("%d\n",a);
// }
}
Related
I have two functions that look like the ones down below and I am trying to merge the two with a function called function3 however I don't want it to check the parameter 'function' everytime it enters the while loop as it is a very poor way to do it. I am wondering if I can merge the two with only one if statement.
void function1(){
int value,a,b;
while(condition){
value=a*b;
}
}
void function2(){
int value,a,b;
while(condition){
value=a+b;
}
}
//merge two functions
void function3(int function){
int value,a,b
while(condition){
if(function==1){
value=a*b;
}
else{
value=a+b;
}
}
}
It is not clear from the code you posted what you intent to do, since you don't actually do anything with the values you calculated.
Aside, I think that you are looking for an array of functions or an array of pointers to functions.
You can use the variable function to access the function that you need, assuming it matches the array index of that function.
int function1(int a, int b) {
return a * b;
}
int function2(int a, int b) {
return a + b;
}
int (*f[])(int, int) = { function1, function2 };
void call_function(int function, int a, int b) {
// check that "function" is within bounds of the array
if (function < 0 || function >= sizeof(f) / sizeof(f[0])) {
// handle out of bounds
}
// call appropriate function
int ret_val = f[function](a, b);
return;
}
Variables declared as auto variables are local to the blocks in which they are defined in C.
Consider the code below,
#include<stdio.h>
#include<string.h>
char *fun();
int main()
{
char *s;
s= fun();
printf("%s\n", s);
return 0;
}
char *fun()
{
char buffer[30];
strcpy(buffer, "RAM");
return (buffer);
}
This is a code I found on net (it was a MCQ question). The output is unpredictable and so throws error since buffer is an auto array and will die when the control go back to main. Thus s will be pointing to an array , which not exists.
Now consider this code.
#include<stdio.h>
int sum(int x,int y)
{
int c=x+y;
return c;
}
int main()
{
int a=1,b=2;
int c=sum(a,b);
printf("%d",c);
}
In this code, the variable c is also an auto variable declared inside the function sum which means it is local to that function and cannot be accessed outside the function. But how does this code compile successfully without throwing any error. Why?
The difference is that in the first example you're returning a pointer with the address to a variable. This pointer is not valid after the variable goes out of scope. In your second example, you're just copying the value of the variable.
This works:
int sum(int x,int y) {
int c=x+y;
return c;
}
But not this
int *sum(int x,int y) {
int c=x+y;
return &c;
}
However, this does, because it's not an auto variable:
int *sum(int x,int y) {
static int c=x+y;
return &c;
}
I understand how to pass a 2D array to a function in C, but I would like to have the function update the original structure rather than a copy of it. How would I go about this? Why does the method I use create a copy of the structure - I was under the impression it was another syntax equivalent to using a pointer?
Thanks for any help. I've included code snippets underneath:
Declaring the variables
int R[rowsize][colsize], G[rowsize][colsize], B[rowsize][colsize];
int Rnew[rowsize][colsize], Gnew[rowsize][colsize], Bnew[rowsize][colsize];
Initialising the function
void blur(int rowsize, int colsize, int R[][428], int G[][428], int B[][428], int Rnew[][428], int Gnew[][428], int Bnew[][428]){
. . .
}
NB: Within this function, Rnew, Gnew and Bnew should be updated - each are a 2D array. I would like this to be done without returning anything.
Calling the function
blur(rowsize, colsize, R, G, B, Rnew, Gnew, Bnew)
You may try this way..
# include <stdio.h>
#define rowsize 3
#define colsize 3
int main()
{
int R[rowsize][colsize]={1,2,3,4,5,6,7,8,9};
int Rnew[rowsize][colsize];
copy_from_R_to_Rnew(R,&Rnew);
int i,j;
for(i=0;i<rowsize;i++)
{
for(j=0;j<colsize;j++){
printf("\t %d",Rnew[i][j]);
}
printf("\n");
}
return(0);
}
void copy_from_R_to_Rnew(int *R,int *Rnew)
{
int i,j;
for(i=0;i<rowsize;i++)
{
for(j=0;j<colsize;j++){
*(Rnew+i*colsize+j) = *(R+i*colsize+j);
}
}
}
I want to pass to a function a pointer that can point to one of several functions.
What is the syntax for this?
void func_a(char c){
//
}
void func_b(char c){
//
}
void receiver(void (*function_pointer)()
{
// do stuff with the pointer to the function, e.g. call it:
function_pointer('a');
function_pointer('b');
function_pointer('c');
}
void main(){
receiver(&func_a); // calls func_a with 'a', then 'b', then 'c'
receiver(&func_b); // calls func_b with 'a', then 'b', then 'c'
}
Will the above work as expected? I assume a function pointer can only be used for functions with the same signature?
Yes, that looks like it should work.
And yes, you can only use the single pointer for functions sharing a signature.
Minor notes:
You don't need to use & to take the address of a function, the function's name evaluates to its address in suitable contexts.
Functions that are local and only intended to be used as callbacks (func_a() and func_b()) should be declared as static.
One thing you can do to make this cleaner is use a typedef. Define your function pointer in a typedef and you can use it in the arguments. Also you don't need the &. Example with your code.
#include <stdio.h>
static void func_a(char c)
{
printf("a:%c\n", c);
}
static void func_b(char c)
{
printf("b:%c\n", c);
}
typedef void (*function)(char c);
void receiver( function func )
{
func('a');
func('b');
func('c');
}
void main()
{
receiver(func_a);
receiver(func_b);
}
I learned this from 'learn C the hard way' link: http://c.learncodethehardway.org/book/ex18.html
Function pointer to select one function among multiple functions
#include <stdio.h>
int plus(int a,int b){return a+b;}
int minus(int a,int b){return a-b;}
int multiply(int a,int b){return a*b;}
int divide(int a,int b){return a/b;}
int percentage(int a,int b){return a%b;}
void gec(int(**p)(int ,int),int c)
{
c=c%5;
if(c==0)
*p=plus;
else if(c==1)
*p=minus;
else if(c==2)
*p=multiply;
else if(c==3)
*p=divide;
else
*p=percentage;
}
int main(void) {
int a=100,b=20,c=12,r;
int(*fptr)(int,int)=NULL;
gec(&fptr,c);
r=(*fptr)(a,b);
printf("%d",r);
return 0;
}
I have this "simple" problem: I have in input 2 int numbers and i must output them in decreasing order.
#include <stdio.h>
#include <iostream>
int fnum()
{
int NUM;
scanf("%d",&NUM);
return NUM;
}
void frisultato(int x,int y)
{
if (x>y)
{
printf("%d",x);
printf("%d",y);
}
else
{
printf("%d",y);
printf("%d",x);
}
return;
}
int main()
{
int A,B;
A=fnum;
B=fnum;
frisultato(A,B);
}
I recieve an error at
A=fnum;
B=fnum;
my compiler says: invalid conversion from int(*)() to int.
This is the first time i use functions, what is the problem? Thank you!
Michelangelo.
A=fnum;
B=fnum;
You're not actually calling the function fnum here. You're attempting to assign a pointer to the function to the int variables A and B.
To call the function, do this:
A=fnum();
B=fnum();
Sorry, but since you seem to be new at programming, I couldn't help but refactor/comment on your code:
#include <stdio.h>
#include <iostream>
int fnum()
{
int num;
scanf("%d",&num);
return num;
}
void frisultato(int x, int y)
{
if (x>y)
{
printf("%d",x);
printf("%d",y);
}
else
{
printf("%d",y);
printf("%d",x);
}
/* No need to return in void */
}
int main()
{
/*
Variables in C are all lowercase.
UPPER_CASE is usually used for macros and preprocessor directives
such as
#define PI 3.14
*/
int a, b;
a = fnum(); //Function calls always need parenthesis, even if they are empty
b = fnum();
frisultato(a, b);
/*
Your main function should return an integer letting whoever
ran it know if it was successful or not.
0 means everything went well, anything else means something went wrong.
*/
return 0;
}
Also, don't sign your name on StackOverflow questions.