454b 454b - 1 year ago 62
C Question

passing value obtained in one function to another function. C language

I am writing a program, that is encrypting a number, entered by user. Encryption steps are performed by functions, which I have to write. The problem is that I have to use value obtained in one function, in the next function. Here is what I am trying to do:
first function reads an integer. second adds 4 to every digit of that integer. and the problem is that how to use the integer that is entered in the first function, in the second function.

void input(int *num)
int numin;
printf("Please enter an integer greater than 99999: ");
scanf("%d", &numin);
while (numin<99999)
printf("Incorrect input.\n");
printf("Please enter an integer greater than 99999: ");
scanf("%d", &numin);
printf("The number entered is %d\n", numin);
int add4(int num)
int a,b=1,numplus4;
int i=-1;
for (numplus4=0; b==0;)
if (a>9)
numplus4+=a*pow(10, i);
printf("%d\n", num);
return num;

I have googled on this topic: but all i got didnot help me, most of answers are for Javascripts, but I am using C.

Answer Source

You are not actually returning anything from the input function.

Instead of passing a pointer to the number being set (which you do not set correctly) you should use the return statement to return the value:

int input(void)

    return numin;

Then you can use it as this:

int main(void)
    int result = add4(input());
    printf("Result is %d\n", result);

    return 0;

The reason you don't return anything in your current function, is because in the input function the parameter num is local to that function. So any changes you made to it (like assigning to it) is lost when the function return.

What you are doing is potentially dangerous as it borders on undefined behaviour. You want to make the pointer point to a local variable, but when the function returns the memory where that local variable is stored is no longer valid to access.

You can use pointer arguments to return values though, this is what is called passing arguments by reference. But you don't assign pointer like you do, instead you use the dereferencing operator (unary *):

*num = numin;

For it to be valid though, you have to pass the address of an already allocated variable, like this:

int num;
input(&num);  /* Use the address-of operator to create a pointer */

However, I suggest using the solution in the first part of this answer, until you know more about pointers and how they work.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download