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

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 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.

You have to dereference the pointer in order to save the inputted value to the memory location pointed to by the pointer:
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);
*num=numin; // <-- This line needs the '*' at the beginning
}

The value obtained in one function can be used in the another function if the variable is declared as static variable.

Related

printf after scanf always displays 1 (same unexpected value)

Okay so I'm trying to do a basic program in VS. Enter a number then it gets printed out. 1 is always printed.
int main(){
printf("Enter an integer: ");
int n = scanf_s("%d", &n);
printf("%d", n);
}
You are assigning the returned value from scanf_s() to the variable n, that means that the program will print 1 in case a successful read happened.
What you should do is
int numberOfItemsMatched;
int readValue;
numberOfItemsMatched = scanf_s("%d", &readValue);
if (numberOfItemsMatched == 1)
printf("%d\n", readValue);
I hope the variable names are self explanatory, and it's always a good idea to use this kind of names.
return type of scanf is number of items read. so if scanf is succesful in reading an item, it returns one which is assigned to n here. hence the output is 1. So separate declaration of n and scanf.

unexpected result when i entered character instead of integer value in scanf

here is my code where i am facing a problem regarding datatypes in c
#include<stdio.h>
int main()
{
int a,b;
scanf("%d",&b);
printf("%d",b);
}
When In Entered Any Character Instead Of Integer values It always Prints 32. Am Not Getting Why Its printing 32.
The value that gets printed is completely arbitrary. It is a result of undefined behavior, because b remains unassigned.
You need to check that the user has entered a value before proceeding. scanf returns the number of items that it has processed, so your code should not use the value unless scanf has returned 1, indicating that one item has been read successfully:
int b;
for (;;) { // Repeat forever
int numRead = scanf("%d",&b);
if (numRead == 1) {
// We've got our number; end the loop:
break;
}
printf("You did not enter a number\n");
// Consume the data that cannot be interpreted as a number.
// Asterisk means "discard the value":
scanf("%*s");
}
printf("b=%d\n", b);
Demo.
If you try the following modification, you might get some insight:
#include<stdio.h>
int main()
{
int a, b;
a = scanf("%d",&b);
printf("%d %d",a,b);
}
When you type anything other than an integer, scanf returns 0, meaning that none of the items in the argument list was successfully filled. That means b has whatever value it had before the call to scanf. Since b is never initialized, this value is undefined.
P.S. Your main function should return type int, not void.

Why variables set in a function are lost?

I am trying to pass the parameters in c through a function. The version with a string argument is working fine but both versions with integer arguments are returning 1 as a result.
#include<stdio.h>
void main()
{
char s1[10];
int a,b;
clrscr();
printf("name=%s\n",getname(s1));
printf("mobile=%d\n",getmobile(a));
printf("mobile=%d\n",getrno(b));
getch();
}
getname(char s[10])
{
printf("enter the name\n");
gets(s);
return ;
}
getmobile(int a)
{
printf("enter the mobile number\n");
scanf("%d",&a);
}
getrno(int b)
{
printf("enter the rno\n");
scanf("%d",&b);
}
The reason why your getname works is but getrno doesn't is because of pass-by-reference vs. pass-by-value semantics and because arrays, like s1 decay to pointers. These are important concepts to understand if you want to program in C.
Think of it like this: When you call getname it accepts a local copy of the address of a buffer. The function then writes into the buffer itself. But when you call your getrno the function accepts a local copy of an integer and reads the value into that local copy, so that nothing changes in the program outside.
#askmish has proposed a good solution, but I would strongly advise something like this instead:
// getrno will prompt the user to enter the rno and will store it into the variable
// pointed to by b. If the function returns 1 then a value was successfully read.
int getrno(int* b)
{
// make sure that the pointer looks valid
if (b == NULL)
return 1;
// prompt the user to enter the text
puts ("enter the rno: ");
// Note the use of a single space at the beginning of the format string
// which is used to consume any whitespace (including return characters
// that might be present)
if (scanf (" %d", b) == 1)
return 0;
// We couldn't read one integer. Return an error.
return 1;
}
int main()
{
int x;
if (!getrno (&x))
printf ("rno = %d\n", x);
else
printf ("failed to get rno!");
return 0;
}
You ask how to go about doing floating-point numbers. The solution is to write a function which accepts, as necessary, either a float or a double pointer and which then calls scanf with the correct format specifier, to read the value into that pointer. This function would look very much like the getrno I showed you above.
Functions should be written like this, for example:
int getrno(int b)
{
printf("enter the rno\n");
scanf("%d",&b);
return b;
}
to get a return value aka, it must have a return-type and a return statement returning value of the specified return-type. Your code had both missing.
I would also suggest to read a good book in C or atleast this page in wikibooks, to understand better and writing better code.

Sorting Strings in a static array based on their length crashes? |wrong allocation/access|

I wanted to make an array of strings and sort them in order based on their length (smallest -> biggest) but the program crashes after all inputs.
And also it bypasses Element 0 (starts directly from element 1 during input)
#include <stdio.h>
#include <stdlib.h>
main()
{
int i,j,N;
printf("\nInput amount of alphanumericals: ");
scanf("%d",&N);
{
int min;
char *swap=(char*)malloc(sizeof(char)*150);
char *A[N],**temp;
for(i=0;i<N;i++)
*(A+i)=malloc(sizeof(char)*N);//Error Here
temp=A;
for(i=0;i<N;i++){
printf("\nInput %d element:",i+1);
fgets(temp+i,150,stdin);//And Here
}
printf("\n\nData [");
for(i=0;i<N;i++)
printf(" %s",A[i]);
printf(" ]\n\n");
//insertion sort
for(i=0;i<N;i++){
min=i;
for(j=i+1;j<N;j++){
if(strcmp(A[j],A[min])<0){
min=j;
}
}
if(min!=i){
swap=A[i];
A[i]=A[min];
A[min]=swap;
}
}
free(swap);
printf("\n\nInsertion Sorted Data [");
for(i=0;i<N;i++)
printf(" %s",A[i]);
printf(" ]");
}
return 0;
}
This error :
for(i=0;i<N;i++)
*(A+i)=malloc(sizeof(char)*N);//Error Here
i reproduced with g++ compiler, if this is your case also i.e. you also compiling with g++ add casting to char* :
*(A+i)= (char*) malloc(sizeof(char)*N);//Error Here
The second issue is because you trying to pass char** instead of char*
fix :
fgets(*(temp+i),150,stdin);//And Here
Also brackets after scanf("%d",&N); limits scope of variables min and swap , so later should not be visible at all.
First, what happens with element 0: after you enter the number of elements which is read by scanf("%d"), you press Enter so that your input reaches the program. But the scanf calls only reads the number, not the newline character. So the first call to fgets gets what remains of the line — an empty line.
See Get scanf to quit when it reads a newline? for several approaches to solve this problem. The most robust way is to call fgets to read a line (which is expected to call the number), then call sscanf to parse the number in the string in memory.
The second problem is in the call fgets(temp+i,150,stdin). A good compiler would produce a warning like this:
a.c:17:9: warning: passing argument 1 of ‘fgets’ from incompatible pointer type [enabled by default]
You're passing a pointer to a pointer to char (the address of a location containing the address of a string buffer), but fgets expects a pointer to char (the address of a string buffer). Since temp+i is a pointer to the entry in the array A (which is an array of pointers), what you need to pass to fgets is the value that this pointer points to: *(temp+i), which is more commonly written temp[i]. Given what you do with the variable temp, just drop it and use A.
fgets(A[i], 150, stdin);
After that, your sort routing doesn't always return the correct result, but that's another story.

Adding numbers until a negative is encountered

I'm trying to create a program that lets the user enter numbers(maximum entries>10^6) until a negative is encountered. I've tried a lot of version but they either don't register that a negative value is entered or they crash.
This is where I'm currently at:
#include <stdio.h>
#define HIGHEST 999999
int main(){
int i=0, entry, sum=0;
while(i<HIGHEST){
scanf("%i", entry);
if(entry>0){
sum+=entry;
}
else{
i=HIGHEST;
}
i++;
}
printf("Sum: %i", sum);
system("pause");
}
Your problem is on this line:
scanf("%i", entry);
Which should be:
scanf("%i", &entry);
You need to pass in the address of the integer variable that will store the scanned value. Since
entry was never initialized, it is just filled with garbage/whatever is in memory and not the entered value. See this reference, which states,
"Depending on the format string, the function may expect a sequence of additional arguments,
each containing a pointer to allocated storage where the interpretation of the extracted
characters is stored with the appropriate type"
You provide a way to leave if the entered number is too big:
while(i<HIGHEST){
But nothing to leave if it is less than 0; Try this:
while((i<HIGHEST)&&(i>=0)){
Additionally, #OldProgrammer is correct, your scanf() should be as he has pointed out.

Resources