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.
Related
I am new to C so I started playing around with some code. I have a bug in my code as I believe using printf(pass) is not safe to use because it can overwrite the value and hence not safe for the user. I was wondering am I right about it that printf(pass) is not safe in my code? Also, how can I still let user print the message finally logged in without changing my code. Is there any way to do that?
My code:
#include <stdio.h>
char pass[100];
char getPass() {
int value = 'G';
int * j = & value;
fgets(pass, sizeof(pass), stdin);
printf("your entered pass is ");
printf(pass);
return (char)( * j);
}
void main() {
printf("enter the pass here ");
if (getPass() == 'K') {
printf("finally logged in\n");
exit(0);
} else {
printf("Wrong password\n");
exit(1);
}
}
Yes it's unsafe, but not for the reason you suggested. If you check the man page for the printf() function, you'll see it has the following prototype:
int printf(const char * restrict format, ...);
The const modifier applied to the first argument specifies that the value of this parameter will not be changed when you call this function.
However, you'll also notice that this parameter is called format. That's because it's supposed to specify a format string. In your program, there's nothing to stop a user entering a format specifier like %p, in which case your call to printf() will start printing out the contents of the stack. There's a Wikipedia article that describes this vulnerability in more detail.
The function fgets if its call was successful provides a string that you can output.
A problem can arise if the obtained string is outputted such a way
printf(pass);
and contains conversion specifiers.
So instead of that call
printf(pass);
it is a more safer to use
printf( "%s", pass );
or
puts(pass);
Preliminary you can remove the new line character stored in the string by the call of fgets.
i'm attempting to create a program that asks the user to firstly enter the amount of values they would like to convert from lowercase to uppercase. The for loop then assigns each value into an array. The array then goes through another for loop to convert the values into uppercase using LowerToUpper function.
When i go to run the program, it will take in values and then start doubling them on the command window, and will cease when you have completed entering the values, rather than printf the results. Could you please explain why. Thank you in advance
#include<stdio.h>
#include <string.h>
#include <ctype.h>
void LowerToUpper(char* array)
{
toupper(*array);
}
int main(void)
{
int i, amount;
printf("How many values?\n");
scanf("%d", &amount);
char *d;
char array1 [amount];
printf("Please enter the values\n");
for(i=0; i<amount; i++)
{
scanf("%c", &array1[i]);
}
for(i=0; i<amount; i++)
{
d=&array1[i];
LowerToUpper(d);
scanf("%c", &array1[i]);
printf("%c", array1[i]);
}
return 0;
}
You are not using toupper() properly. The function returns the converted value in case of success. You need to make use of the returned value. The supplied argument is not changed.
That said, the program structure is unnecessarily complicated. you can simplify it like
for(i=0; i<amount; i++)
{
int result = toupper (array1[i]);
if (result != array1[i]) printf("%c", result); //just checkin', if converted
}
That said, you have many other issue which you don't see at this moment, like
scanf("%c", &array1[i]);
this will, to your surprise, only ask you for half the number of inputs. Why? You forgot to ignore the newline entered by RETURN key.
Then, you did not check for the success of scanf("%d", &amount); call. In case, the scanning fails, you'll end up with undefined behavior.
The second scanf() inside the last for loop is probably something you don;t want, it's useless, at best.
Change this:
toupper(*array);
to this:
*array = toupper(*array);
since toupper ref's mentions:
Return Value
The uppercase equivalent to c (*array in your case), if such value exists, or c (unchanged) otherwise. The value is returned as an int value that
can be implicitly casted to char.
PS: Defining a function LowerToUpper() for this operation (one line of code) is an overkill, and you could call that one line of code inside main() instead (I mean the body of the function to be moved into main()).
I am trying to use a number after it has been taken as input using "scanf" function. For example if I input 2 I want to know how I can use that in the later stages of my code(maybe call another function with it).
#include<stdio.h>
int main(){
int Input;
scanf("%d",Input);
printf("%d", Input);
//here is the place where I want to use the Input
return 0;
}
In the code example, after command printf how should I further develop the code.
Im not sure if this answers your question. You dont have to print the value to use it. you can simply use it anywhere after you have taken it from scanf.
#include<stdio.h>
int inc(int input) {
int val = input + 1;
return val;
}
int main(){
int Input;
scanf("%d",&Input); //dont forget &
//now you have the input saved, do anything you want with Input
printf("%d",Input); // you can print the value you scanned
int out = inc(Input); //you can put it in a new function
printf("%d %d",Input,out); //you can output it again, "printf" is also another function
return 0;
}
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.
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.