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);
}
num=&numin;
printf("The number entered is %d\n", numin);
return;
}
int add4(int num)
{
int a,b=1,numplus4;
int i=-1;
for (numplus4=0; b==0;)
{
a=num%10;
b=num/10;
num=b;
a+=4;
if (a>9)
a-=10;
i++;
numplus4+=a*pow(10, i);
}
num=numplus4;
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.
You are not actually returning anything from the
inputfunction.Instead of passing a pointer to the number being set (which you do not set correctly) you should use the
returnstatement to return the value:Then you can use it as this:
The reason you don’t return anything in your current function, is because in the
inputfunction the parameternumis 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
*):For it to be valid though, you have to pass the address of an already allocated variable, like this:
However, I suggest using the solution in the first part of this answer, until you know more about pointers and how they work.