Call a Function Many Times - (Passing a Function as a Parameter) – C - c

So the code below can be used to pass a function as a parameter:
void printNumber(int nbr)
{
printf("%d\n", nbr);
}
void myFunction(void (*f)(int))
{
for(int i = 0; i < 5; i++)
{
(*f)(i);
}
}
int main(void)
{
myFunction(printNumber);
return (0);
}
But how can I change that code so that the integer for “printNumber” is defined outside of “myFunction”? In other words I only want to call the function “myFunction” for x number of times with the same integer .
I wrote some pseudocode to explain what I'm trying to accomplish:
void printNumber(int nbr)
{
printf("%d\n", nbr);
}
void myFunction(void (*f)(*int)) //pseudocode
{
for(int i = 0; i < 5; i++)
{
(*f)(*int); //pseudocode
}
}
int main(void)
{
myFunction(printNumber(5)); //pseudocode
return (0);
}

printnumber(5) means to call printnumber immediately and pass it 5. You want to pass printnumber and 5 separately as two arguments
void printNumber(int nbr)
{
printf("%d\n", nbr);
}
// void (*f)(int) is a pointer to a function that takes an int
// arg is the int to pass in
void myFunction(void (*f)(int), int arg)
{
for(int i = 0; i < 5; i++)
{
// call f and pass in arg
(*f)(arg);
}
}
int main(void)
{
// pass the function and the arg to use
myFunction(printNumber, 5);
return (0);
}

You need another argument.
void printNumber(int nbr)
{
printf("%d\n", nbr);
}
void myFunction(void (*f)(int), int Arg)
{
for(int i = 0; i < 5; i++)
{
(*f)(Arg);
}
}
int main(void)
{
myFunction(printNumber, 42);
return (0);
}
The parameter declaration void (*f)(int) only says that the function pointed to by f expects an int. It doesn't mean that an int is also packed into the function pointer somehow.

Related

Passing variable from mulitple functions to another function in C

Basically I need to pass the ret variable from the functions checkPOS, checkPOS1, checkPOS2 to the result() function, if the sum of the 3 ret variables equals to zero, user's access is granted, in case it is 1+, the access is denied. How can I pass the 3 variables to the result function?
void checkPOS2(struct Node* n, int pos, int alg, int input) {
int ret3;
for (int i = 0; i < pos - 1; i++) {
n = n->next;
}
if (input == n->data[alg]) {
printf("Numero certo (");
printf("%d", n->data[0]);
printf("%d", n->data[1]);
printf("%d)", n->data[2]);
ret3 = 0;
return ret3;
}
else {
printf("Numero errado (");
printf("%d", n->data[0]);
printf("%d", n->data[1]);
printf("%d)", n->data[2]);
ret3 = 1;
return ret3;
}
}
void result() {
if ((ret3) == 0) { printf("Acesso Permitido!"); }
else { printf("Acesso Negado!"); }
printf("%d", ret3);
}
It needs to take parameter as well.
void result(int r)
{
if ((r) == 0) { printf("Acesso Permitido!"); }
else { printf("Acesso Negado!"); }
printf("%d", r);
}
and before you call it:
int res = checkPOSx(....);
result(res);
or
result(checkPOSx(....));

why this show() function produce two * and the element will stop sometimes .There is no error in the code

This is a plane game function I wrote. I use a two-dimensional array to represent the game variables but The running result is abnormal, and * will jump suddenly.
And there will be two * , at the same time, and the plane also will stop
There should be no two * in the process of traversing the two-dimensional array. I tried to modify the position of * but I still couldn't.It's OK to run part of the code alone, but when you use the key operation, the program makes an error, but I don't know what's wrong
#include<stdio.h>
#include <windows.h>
#include<stdlib.h>
#include<conio.h>
#define enemynum 3
int element [20][30];
int position_x,position_y;
int enemy_x[enemynum],enemy_y[enemynum];
int score;
void gotoxy(int x, int y)
{
HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);
COORD pos;
pos.X = x;
pos.Y = y;
SetConsoleCursorPosition(handle, pos);
}
void HideCursor()
{
CONSOLE_CURSOR_INFO cursor_info = {1,0};
SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cursor_info);
}
void startup()
{ element[20][30]={0};
position_x=10;position_y=15;
element[position_x][position_y]=1;
for(int k=0;k<enemynum;k++)
{
enemy_x[k]=rand()%3;enemy_y[k]=rand()%20;
element[enemy_x[k]][enemy_y[k]]=3;
}
HideCursor();
}
This is an encapsulated pointer callback function. I don't think we need to consider the above functions
void show()
{ int i,j;
gotoxy(0,0);
for(i=0;i<20;i++)
{
for(j=0;j<30;j++)
{ if(element[i][j]==1)
{
printf("*");
}else if(element[i][j]==3)
{
printf("#");
}
else
printf(" ");
}
printf("\n");
}
}
void updatewhithout()
{
int i,j;
for(i=0;i<20;i++)
{
for(j=0;j<30;j++)
{
if(element[i][j]==2)
{
element[i][j]=0;
if(i>0)
element[i-1][j]=2;
}
}
} static int flag;
if(flag<20)
flag++;
if(flag==20)
{ for(int k=0;k<enemynum;k++)
{
if(enemy_x[k]==20)
{
enemy_x[k]=rand()%3;
enemy_y[k]=rand()%20;
}
element[enemy_x[k]][enemy_y[k]]=0;
enemy_x[k]++;
element[enemy_x[k]][enemy_y[k]]=3;
flag=0;
}
}
}
void updatewhith()
{ char ch;
if( kbhit())
ch=getch();
if(ch=='a')
{ element[position_x][position_y]=0;
position_y--;
element[position_x][position_y]=1;
}
if(ch=='d')
{ element[position_x][position_y]=0;
position_y++;
element[position_x][position_y]=1;
}
}
int main()
{startup();
while(1)
{show();
updatewhithout();
updatewhith();
}
}

problem reading 2d array after passing a ponter from one function to another

I'm trying to read from a 2D array I have declared in my main function but while being in a different function. I thought that if I will send a pointer to the first cell of that array then this will be possible, however I'm still having problem doing it
The issue is passing a 2d array which I have declared in my main function to another function, which itself is called from another function. I know this is a basic question but after many tries I still can't understand what I'm doing wrong and would sincerely appreciate your help.
I've simplified the following code the problem in the following code:
void main(){
N = 5, M = 4
double arr[][4] = {
{ 1,2,1,5 },
{ 8,9,7,2 },
{ 8,7,6,1 },
{ 5,4,5,3 },
{ 5,4,5,3 }
};
double(*pointer)[4]; // pointer creation
pointer = arr; //assignation
function_1(pointer ,N,M);
}
function_1(double *arr, int N, int M){
function_2(arr,N,M);
}
function_2(double *arr, int N, int M){
int c = 0;
for(int i=0; i<n; i++){
for(int j=0l j<M; j++){
arr[i][j] = c; // error while trying to read from arr[i][j]
c += 1;
}
}
}
I have specefique the len of array in all of the function
function_2(double arr[5][4], int N, int M)
{
int c = 0;
for(int i=0; i<N; i++)
{
for(int j=0; j<M; j++)
{
arr[0][0] = c;
c += 1;
}
}
}
void function_1(double arr[5][4], int N, int M)
{
function_2(arr,N,M);
}
int main()
{
int N = 5, M = 4;
double arr[][4] =
{
{ 1,2,1,5 },
{ 8,9,7,2 },
{ 8,7,6,1 },
{ 5,4,5,3 },
{ 5,4,5,3 }
};
function_1(arr ,N,M);
return 0;
}

C trouble with function calling with pointers

I'm using a structure array to save data about specific person, and have 2 function which write out data. 3rd function (Wypisz) uses pointer to use specified one. The problem is when i try to compile it, error occurs in this function in both 'if clauses':
error: expected expression before 'struct'
struct Osoba
{ char imie[MAX], nazwisko[MAX];
int rokurodzenia[N];
};
void WypiszWLinii(struct Osoba osoba[])
{ int i;
for(i=0;i<N;i++)
{
printf("%c %c, %d\n", osoba[i].imie, osoba[i].nazwisko, osoba[i].rokurodzenia);
}
}
void WypiszJedenPoDrugim(struct Osoba osoba[])
{
int i;
for(i=0;i<N;i++)
{
printf("%c\n%c\n%d\n", osoba[i].imie, osoba[i].nazwisko, osoba[i].rokurodzenia);
}
}
void Wypisz(void (*wskfun)(struct Osoba), int i)
{
if(i=1)
{
wskfun=WypiszJedenPoDrugim(struct Osoba osoba[]);
}
else if(i=0)
{
wskfun=WypiszWLinii(struct Osoboa osoba[]);
}
else
{
printf("Wybrano zla opcje w menu\n");
return -1;
}
}
N and MAX is predefined variable with library inclusions
the problem you have in the Wypisz function implementation is the assignement of pointer to a function to a wrong value.
Instead to :
wskfun=WypiszJedenPoDrugim(struct Osoba osoba[]);
or
wskfun=WypiszWLinii(struct Osoba osoba[]);
you have to get the pointer to that function and assing it to the variable:
wskfun = &WypiszJedenPoDrugim;
or
wskfun = &WypiszWLinii;
After that you could use the pointer to the function like:
wskfun("pointer to struct array");
Said that, to solve your problem the function must be changed like:
void Wypisz(void(*wskfun)(struct Osoba[]), int i)
{
if (i = 1)
{
wskfun = &WypiszJedenPoDrugim;
}
else if (i = 0)
{
wskfun = &WypiszWLinii;
}
else
{
printf("Wybrano zla opcje w menu\n");
return -1;
}
}

Problem with calling a function?

If I have those functions:
void main(void)
{
char *menu[] = {"data", "coming", "here"};
prints(**************); // here
printf("\n");
}
void prints(char **menu)
{
int a;
while(*menu)
{
printf("%s", **menu);
menu ++;
}
a = 0;
}
How to call prints function ???
Here is a version with several issues fixed:
#include <stdio.h>
// declare function before using it
void prints(char **menu)
{
// make sure parameter is valid
if (menu != NULL)
{
while(*menu)
{
// spaces so they don't run together
// pass *menu not **menu to printf
printf("%s ", *menu);
menu ++;
}
}
}
// proper return type for main()
int main(void)
{
// array terminator added
char *menu[] = {"data", "coming", "here", NULL};
prints(menu); // here
printf("\n");
// return with no error
return 0;
}
In C you must declare your function before another function that uses it. So...
void prints(char **menu)
{
int a;
while(*menu)
{
printf("%s", **menu);
menu ++;
}
a = 0;
}
void main(void)
{
char *menu[] = {"data", "coming", "here"};
prints(**************); // here
printf("\n");
}
That, or you can forward declare the function:
void prints(char **menu);
void main(void)
{
char *menu[] = {"data", "coming", "here"};
prints(**************); // here
printf("\n");
}
void prints(char **menu)
{
int a;
while(*menu)
{
printf("%s", **menu);
menu ++;
}
a = 0;
}
You can either move the prints function above main, or you can put a prototype for prints above main, like so:
void prints(char **menu);
Then, you can call prints from main just like any other function...

Resources