Function parameter in C not modified after function is called - c

#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
#include<time.h>
double gen(double dS) //Function for a random double variable
{
double dx=0;
dx=rand()%200+1;
dS=dx/100;
return(dS);
}
int main()
{
double dZahl=0;
double dTokens=1;
srand((unsigned)time(NULL));
double dSummand=0;
int iGame=0;
for(;;)
{
printf("Deine Tokens:%.2lf\n", dTokens); //This doesn't really matter
printf("Was m%cchtest du tun?\n[1]:Generiere Tokens\n[2]:Spiele ein Minigame\n", 148);
fflush(stdout);
scanf("%d", &iGame);
fflush(stdin);
switch (iGame)
{
case 1:
{
gen(dSummand); //function in use
dTokens=dTokens+dSummand;
printf("\nDu hast %.2lf Tokens generiert!\n", dSummand); //the output of the value
fflush(stdout);
}
break;
}
}
getch();
}
The problem is that dSummand doesn't get the value from dS. Does anyone know what the problem is because I was trying to fix it but I couldn't figure it out.
I am trying to get a random double value with a function for my program. I thought it would work like this but unfortunately it didn't.

If you want the value for dS to come out of the function modified you have to pass a pointer.
double gen(double *dS) {
*dS=dx/100;
and then
gen(&dSummand);

Related

C: Function not behaving as intended when called by "if" statement

I'm a C beginner and am working on a program that registers flights using structs. Each flight has a code that must follow a certain structure: FLI-XXXX, X being integers. I'd like to use the integers part of the code later on, so I thought the best way to scan for it was using both fgets and scanf. After validating the code using auxiliary variables, I would later write it to the flights struct. However, I'm stuck at the validating part.
The problem is, whenever I call the function that validates a code (opt1) inside an if statement, it runs twice and only works as intended the second time around. Here's my code:
#include <stdio.h>
#include <string.h>
typedef struct
{
int num;
char code[5];
}fl;
fl flight[9999];
int Valid(char a[], int b)
{
if((strlen(a) != 4) || (b<0 || b>9999)){
return 0;
}
else if(a[0] !='F' || a[1] !='L' || a[2] !='I' || a[3] != '-'){
return 0;
}
return 1;
}
void opt1(fl a[]){
char tempCode[5];
int tempNum;
do
{
puts("Insert code:");
fgets(tempCode, 5, stdin);
scanf("%d", &tempNum);
puts("");
if (Valid(tempCode, tempNum))
{
printf("Flight %s%d registered. \n", tempCode, tempNum);
}
else
{
puts("Flight # invalid.");
}
} while (Valid(tempCode, tempNum)==0);
}
int main() {
int opt;
//calling opt1 works as intended
opt1(flight);
//calling inside if statement runs opt1() twice, only the second time as intended
scanf("%d", &opt);
if(opt==1){
opt1(flight);
}
return 0;
}
And here's an input:
FLI-1234
1
FLI-1234
That returns:
Flight FLI-1234 registered.
Insert code:
Flight # invalid.
Insert code:
Flight FLI-1234 registered.
I'm not sure why this is happening. Can anyone guide me in the right direction, please? Thank you.

Recursive function is not working with a pointer

This function aims to return the number of zeroes in a number, num. The function rCountZeros2() passes the result through
the pointer parameter result.
`
void rCountZeros2(int num, int *result)
{
if (num==0)
return;
else
{
if (num%10==0){
(*result)++;
}
rCountZeros2(num/10, result);
}
}
`
See when you are invoking rCountZeros2() , my guess is value in variable result is not zero.It may be some garbage value or some other value from previous computation.However with details you have provided it is difficult to provide exact answer.
Kindly try the following standalone program, I got correct answer using your code
void rCountZeros2(int num, int *result)
{
if (num==0)
return;
else
{
if (num%10==0){
(*result)++;
}
rCountZeros2(num/10, result);
}
}
int main()
{
int result = 0;
int num=12300000;
rCountZeros2(num, &result);
printf("number of zeros in %d = %d",num ,result);
}

how to assign/initialize the array of function pointers only when i call a function to do so

#include <stdio.h>
#include <stdlib.h>
int (*(*ptr[2])[2])(); //arr of pointers to the array of func pointer
int (*arr_1[2])(int ,int);//arr of function pointers
(*arr_1[])()={add1, sub1};//add1 ,sub1 are simple functions returning int
int (*arr_2[2])(int ,int);
int a,b, user_func_choice;
(*arr_2[])()={add2, sub2};
int lib_choice,user_lib_choice;
int main(int argc , char* argv[]) {
printf("enter the lib number\t 1:Lib1 , 2:Lib2 \n");
scanf("%d", &user_lib_choice);
lib_choice=user_lib_choice-1;
if(lib_choice==0){
printf("Welcome to lib1\n");
printf("enter func choice==> 1: Add , 2: subtract\n");
scanf("%d", &user_func_choice);
printf("enter the numbers.\n");
scanf("%d%d",&a,&b);
int func_choice= user_func_choice-1;
ptr[0]= arr_1;
if(func_choice==0)
{
int sum1=(*(*ptr[lib_choice])[func_choice])(a,b);
printf("sum1=%1d\n\n", sum1);
}
else if(func_choice==1)
{
int subtract1=(*(*ptr[lib_choice])[func_choice])(a,b);
printf("sub1=%1d\n\n", subtract1);
}
else{printf("InValid Function/operator choice\n");}
return;
}
if(lib_choice=1){
int a, b, user_func_choice;
printf("welcome to lib2\n");
printf("enter func choice: 1: Add , 2: subtract\n");
scanf("%d", &user_func_choice);
printf("enter the numbers.\n");
scanf("%d%d",&a,&b);
ptr[1] = arr_2;
int func_choice= user_func_choice-1;
if(func_choice==0)
{
int sum2=(*(*ptr[lib_choice])[func_choice])(a,b);
printf("sum2=%1d\n\n", sum2);
}
else if(func_choice==1)
{
int subtract2=(*(*ptr[lib_choice])[func_choice])(a,b);
printf("sub2=%1d\n\n", subtract2);
}
return;
}
else{printf("InValid library choice\n");
}
return 0;
}
Every thing works fine here
But what i want is instead of hardcoding the initialization of library(lib1 or lib2) let user specify the number of libraries he want to intialize. Something like this
int main(int argc , char* argv[]){
printf("enter the lib number\t 1:Lib1 , 2:Lib2 \n");
scanf("%d", &user_lib_choice);
if(argc!=2){printf("please specify the library number as sencond argument\n");return 0;}
int lib_choice_cmd=atoi(argv[1]);
if(lib_choice==1)
{
lib1_init();
}
else if(lib_choice==2)
{
lib1_init();
lib2_init();
}
lib_init() is the function that will do the initialization process.If user specify lib num as 1 i will initialize only lib1. I did this for lib1, but this gives me an error
lib1_init(){
(*arr_1[2])(int ,int)={add1 , sub1};
}
And when i did
lib1_init(){
arr_1[0]=add1;
arr_1[1]=sub1;
}
This gives me a segmentation fault.Pleae tell me what is wrong
You can only do initialization when initializing, not later. Even given that, your syntax looks odd.
You can of course use plain assignment to each element:
void array_init(void)
{
arr_1[0] = add1;
arr_1[1] = sub1;
}
(*arr[2])()={add1 ,sub1};
Unless that line appears on the same line as the function pointer array initialization, it is complete nonsense code.
You can initialize the array upon declaration like this:
int(*arr[2])(int ,int) = {add1 ,sub1};
Or you can assign an individual item, just as for any array:
arr[0] = add1;
In C, you cannot assign arrays to arrays, nor can you assign several array items on a single line. That is, you can't do int arr[2]; arr = {1,2};Function pointer arrays are no different than other arrays.
If you want to initialize the array in run-time, you have to either set each item one by one in a loop, or use memcpy.
I did not right understood the problem, but there is a syntax mistake:
if you declare a pointer to function array like this:
int(*arr[2])(int ,int)
you have to call the function like this:
(*arr[0])(some_int_stuff, some_other_int_stuff);
the mistakes are that the index must be smaller than 2, and you don't pass any parameter

error C2447: '{' : missing function header -- Can't resolve this error, what's wrong?

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <string.h>
#include "bcio2.h"
int error, x;
char totalimpulse[80], averageimpulse[80];
void validate_number();
int main(void)
{
clrscr();
do{
printf("\nTotal Impulse delivered: ");
gets(totalimpulse);
validate_number();
} while (error != 0);
printf("You entry %d was valid\n", x);
getch();
return 0;
}
{ //error C2447
clrscr();
do{
printf("\nAverage Impulse delivered: ");
gets(averageimpulse);
validate_number();
} while (error != 0);
printf("You entry %d was valid\n", x);
getch();
return 0;
}
The brackets seen to match and there doesn't seem to be any unnecessary semicolons. I'm assuming this is the correct way to display input/validation. It works fine when run with just the do…while(); loop for totalimpulse but when I copy/paste the exact same between another pair of { } I get just that C2447 error.
The code that starts where the error is is not inside main, or any other function for that matter. If you remove the braces on the error line and the one preceding it, then your second loop will also beside of main. If you want that section to be a different function, you have to include the header for that function. What you put at the top for validate_number is just a promise that you will define that function somewhere (although if you mean for that section at the bottom to be validate_number, I'm pretty sure you don't want it to be recursive).
Right now you just have a block of code, outside any function.
I'm assuming from the rest of your code, that this block of code is supposed to be the definition of void validate_number();, like this:
void validate_number()
{
clrscr();
do{
// ...
return 0;
}
Do note that a void function cannot return a value, so your return 0 should be removed.

c code on task scheduling

I want to execute this code to run auto taskscheduling as this code has two errors. I'm not able to figure out the corrections.
Errors are "(in function 'main')" and "(invalid lvalue in assignment)"
#include<unistd.h>
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include<string.h>
int main()
{
char *timetoken;
char currtime[7];
char schedtime[9];
int i;
struct tm *localtimeptr;
strcpy(schedtime,"15:25:00");
while(true)
{
time_t lt;
sleep(1);
time(&lt);
localtimeptr = localtime(&lt);
timetoken=strtok(asctime(localtimeptr)," ");
for(i=1;i<5;i++)
timetoken=strtok(NULL," ");
if(i==3)
{
strcpy(currtime,timetoken);
}
}
printf("The current time is: %s\n",currtime);
printf("We are waiting for: %s\n",schedtime);
if(!strcmp(currtime,schedtime))
{
printf("Time to do stuff \n");
system("ROBOCOPY C:\\oslab E:\\BACKUP /e/mir/np /log:backup_log.txt");
}
getch();
return 0;
}
time = (&lt);
You didn't define a variable called time... are you sure this wasn't meant to set a different variable?
time = (&lt);
You're trying to assign to time, but you yourself have never declared anything called time. Accordingly, you're trying to reassign time(3) from time.h.
Maybe you mean something else in this line, like
time(&lt);

Resources