How to get a int with scanf() - c

void pedir_diag(int* diag){
scanf("%i", &diag);
}
int main() {
int number;
pedir_diag(&number);
return 0;
}
When I compile introduce an integer and expect that number int variable in the main have the value introduced but is not set
I have this, in my code but i am not able to set diag variable with scanf() function.

diag is already a pointer so no need for the address-of operator (&) in the call to scanf():
void pedir_diag(int *diag)
{
scanf("%d", diag);
}
But to do it that way is kinda stupid. You have no way to check for erroneous input.
Better:
#include <stdbool.h>
bool pedir_diag(int *diag)
{
return scanf("%d", diag) == 1; // *)
}
*) scanf() returns the number of successful conversions, so if the number of successful conversions is 1 we return true.
Usage:
#include <stdio.h>
int main(void)
{
int foo;
if (!pedir_diag(&foo)) {
fputs("Input error :(\n\n", stderr);
}
else {
// have fun with foo
}
}

The best way to use scanf through your entire coding life is by remembering the following rule
scanf("%[direction_of_what_to_scan][special format character]",
Pointer_on_some_memory_location);
What scanf does is that it stores what the input was (with some length restrictions) to a memory address. So, either:
int n1;
scanf("%d",&n); //which means the address of variable n1 in memory
or
int *n2 = &n1;
scanf("%d",n) // &doesn't need to be used cause n2 is now already pointer to an integer
Both will are different implementations of the same thing, they differ to the part of using pointers,for which C is well-known,and even applicable these days.

Related

Using function to pass the user input via pointers not working

I'm trying to get the input from the user input, and pass to the program main using pointer. It seems that the value isn't going through even tho I tried some alternatives.
For example, if i input 0.0001, when I return to the main function it outputs 0.0000
#include <stdio.h>
void inputFloat(float *n);
int main() {
float *number;
printf("Insert number: ");
inputFloat(number);
printf("%1.4f", *number);
return 0;
}
void inputFloat(float *n){
float num;
while (scanf("%f", &num) != 1 || num < 0) {
scanf("%*[^\n]%*c");
printf("insert positive: ");
}
printf("%1.4f\n", num);
n = &num;
}
Thanks in advance for any tip or correction.
The main problem here is that you forget that in C arguments are passed by value, and that includes pointers.
The argument variable n in the inputFloat function is local to the inputFloat function, all modifications (like assignments) to it will be lost once the function returns.
What I believe you are trying to to is emulating pass by reference, which indeed is done by using pointers. But then you pass a pointer to a normal variable using the address-of operator &:
float number; // Not a pointer
inputFloat(&number); // Pass a pointer to the variable number
To use this pointer, and to set the value of the original variable it points to, you need to dereference the pointer:
void inputFloat(float *n)
{
// ...
*n = num; // Copy the value of num to the location where n is pointing
}

Header files and functions, is my function, parameters, or header prototype?

I just started with C and am tasked with using a header to house a prototype for a function. The problem is that nothing happens when I'm expecting a prompt for input. I didn't get an error and would like to know where to look at first to solve my problem. This is what I have so far.
LAB2.c
#include <stdio.h>
#include "LAB2HEADER.h"
int main(){
double *p;
double array [10];
p = array;
const int size = 10;
void input(p,size);
return 0;
}
LAB2HEADER.h
#ifndef LAB2HEADER_H_
#define LAB2HEADER_H_
void input (double *array,const int size);
#endif
LAB2HEADER.c
#include <stdio.h>
#include "LAB2HEADER.h"
void input (double *array,const int size){
for (int i = 0; i < size ; i++)
{
printf("Input a value");
scanf("%lf", &array[i]);
}
}
A lot of the notes I look at seem to only either use Int as a parameter or have a function with no needed parameters, could my mistake be in my array pointer is it a problem with the way I made my function?
void input(p,size);
This line makes no sense. If this is supposed to be a function call, you need to remove void.
Also, since your print statement does not end with a newline, nor do you flush stdout before reading in the value, your prompt might still be in the output buffer and not be output until you hit the newline AFTER entering the value.

Why this program stops unexpectedly in the middle of the input

i have written this code for a question on codechef (A4)....when i give the input:
2
4 2
This program stops unexpectedly without taking further input ....can some please point out the mistake in the code?
#include <stdio.h>
#include<math.h>
void number(long int a,int b)
{
int c;
c=b;
int first[c],last[c],e=1,i;
long int d;
d=pow(a,a);
for(i=(c-1);i>=0;i--)
{
last[i]=fmod(d,pow(10,e));
e++;
}
e=1;
while(d>pow(10,(b-1)))
d/=10;
for(i=(c-1);i>=0;i--)
{
first[i]=fmod(d,pow(10,e));
e++;
}
for(i=0;i<c;i++)
printf("%d",first[i]);
printf(" ");
for(i=0;i<c;i++)
printf("%d",last[i]);
printf("\n");
}
int main()
{ int T;
scanf("%d",&T);
while(T--)
{ long int a;
int b;
scanf("%ld %d",a,b);
number(a,b);
}
return 0;
}
scanf("%ld %d",&a,&b);
Using uninitialized variables lead to UB. You should use &a and &b to scan variables
In your code you have
scanf("&ld %d",a,b);
It means you're trying to input integers to the memory locations of values of a and b. For and example let value of a = 1234566466 (long int), and b = 1234 (int). Accordingly 1234 is a memory location which is at the start of the RAM. Tn that area System files are loaded. So you are going to change system behaviour. That is not allowed.
Further when the complier allocate some memory space to your program, you can access only the memory which is inside your memory segment directly. But above statement trying to access another segment.
That's why you get segmentatin fault.
You are passing an integer to a function that expects a pointer, for scanf the "%d" and "%ld" specifiers expect int * and long int * respectively, and you pass int and long int, so when trying to access the integers as if they were memory addresses the segmentation fault occurs.
The correct way to call scanf would be as Gopi said
scanf("%ld %d", &a, &b);
there you pass a and b addresses instead of their values.

How to push scanned values to a stack in C?

I guess there is a problem in scanning the values from keyboard to the stack array using scanf. I'm not sure how to enter scanned values to the array in the stack. Please correct my C code. Check my main method where I ask for user inputs and try to push them to the array.
#include<stdio.h>
#define STACKSIZE 5
struct stack
{
float data[STACKSIZE];
int sp;
};
struct stack sta={{0},-1};
//push method
void push(float n)
{
sta.data[++sta.sp]==n;
//onlystack.data[++onlystack.sp]=x;
}
//pop method
float pop()
{
return sta.data[sta.sp--];
}
//top method
float top()
{
return sta.data[sta.sp];
}
//full method
int full()
{
return (sta.sp==STACKSIZE-1);
}
//empty method
int empty()
{
return (sta.sp==-1);
}
int main()
{
int x, y;
int temp;
for (x=0; x<STACKSIZE; x++)
{
**printf("Enter float to be stored in the stack");
scanf("%f", &temp);
push(temp);**
}
while(!empty(sta))
{
for (y=0; y<STACKSIZE; y++)
{
printf("\t%f",pop());
}
}
printf("%f", top());
return 0;
}
Thoughts:
In push(), you test for equality instead of performing assignment.
temp is of type int. It should be a float.
empty() takes no arguments, and you pass it one.
The last printf("%f", top()) will invoke undefined behavior, because you will print sta.data[-1].
You don't really need the while loop and the for loop around the pop() printing. You should be able to just do the while loop.
To make your output more readable, you should probably print '\n' characters after each float, which will make each float be seen on their own line.
Once these errors are fixed, the code appears to work correctly:
code: https://gist.github.com/sharth/3f67f2790e6a337ada47
runtime: https://gist.github.com/sharth/fdd7af6d6630b335df09
A major problem here is that you give the format "%f" (for floating point) to scanf, but you give it a pointer to an int. This will cause the value to be something completely unexpected.
Also, in the loop where you print the values, why have a nested loop? The outer loop is all that's needed.

Declaring arrays in c language without initial size

Write a program to manipulate the temperature details as given below.
- Input the number of days to be calculated. – Main function
- Input temperature in Celsius – input function
- Convert the temperature from Celsius to Fahrenheit.- Separate function
- find the average temperature in Fahrenheit.
how can I make this program without initial size of array ??
#include<stdio.h>
#include<conio.h>
void input(int);
int temp[10];
int d;
void main()
{
int x=0;
float avg=0,t=0;
printf("\nHow many days : ");
scanf("%d",&d);
input(d);
conv();
for(x=0;x<d;x++)
{
t=t+temp[x];
}
avg=t/d;
printf("Avarage is %f",avg);
getch();
}
void input(int d)
{
int x=0;
for(x=0;x<d;x++)
{
printf("Input temperature in Celsius for #%d day",x+1);
scanf("%d",&temp[x]);
}
}
void conv()
{
int x=0;
for(x=0;x<d;x++)
{
temp[x]=1.8*temp[x]+32;
}
}
In C arrays and pointers are closely related. In fact, by design an array is just a syntax convention for accessing a pointer to an allocated memory. *(see note for more details below)
So in C the statement
anyarray[n]
is the same as
*(anyarray+n)
Using pointer arithmetic.
You don't really have to worry about the details to make it "work" as it is designed to be somewhat intuitive.
Just create a pointer, and allocate the memory and then access it like as an array.
Here is some examples --
int *temp = null; // this will be our array
// allocate space for 10 items
temp = malloc(sizeof(int)*10);
// reference the first element of temp
temp[0] = 70;
// free the memory when done
free(temp);
Remember -- if you access outside of the allocated area you will have unknown effects.
To be clear it is the indexing operator ([ ]) that is translated to pointer arithmetic. This is not an array in the modern sense of the
type. Whether (or not) the pointer involved points to (dynamically) allocated
memory is inconsequential to how this operator works. In a more modern language you would be able to operate on the array as an abstract type (to see how big it is, for example), you can't do this in C.
An array without an initial size is basically just a pointer. In order to dynamically set the size of the array, you need to use the malloc() or calloc() functions. These will allocate a specified amount of bytes of memory.
In your code above, declare temp as an int pointer
int *temp;
Then allocate space for it using malloc() or calloc(). The argument that these functions take is is the number of bytes of memory to allocate. In this case, you want enough space for d ints. So...
temp = malloc(d * sizeof(int));
malloc returns a pointer to the first byte in the block of memory that was just allocated. Regular arrays are simply pointers to the first byte in a sectioned off block of memory, which is exactly what temp is now. Thus, you can treat the temp pointer as an array! Like so:
temp[1] = 10;
int foo = temp[1];
printf("%d", foo);
Outputs
10
You will need to declare temp as an int pointer (instead of an int array). Then, you can use malloc in your main (after your first scanf):
temp = malloc(d * sizeof(int));
If your compiler supports c99, then simply use VLA(variable length array).Use like this:
void input(int);
int d;
void main()
{
int x=0;
float avg=0,t=0;
printf("\nHow many days : ");
scanf("%d",&d);
int temp[d];
input(d);
conv();
for(x=0;x<d;x++)
{
t=t+temp[x];
}
avg=t/d;
printf("Avarage is %f",avg);
getch();
}
Now temp[] is defined inside main() after date input.
1-add #include<stdlib.h> at the top of your file. Then modify the conv() code as follows:
2- modify temp declaration as follows (global variable):
int *temp;
3- modify input(int d) function as follows (tested on Visual Studio 2010):
void input(int d)
{
int x=0;
temp=(int*)malloc(sizeof(int)*d);
for(x=0;x<d;x++)
{
printf("Input temperature in Celsius for #%d day",x+1);
scanf("%d",&temp[x]);
}
}
Allocate the "array" dynamically on the heap after you read the size.
I didn't change anything else so you may see it clearly.
#include<stdio.h>
#include<conio.h>
#include <stdlib.h> //here
void input(int);
int *temp=0; //here
int d;
void main()
{
int x=0;
float avg=0,t=0;
printf("\nHow many days : ");
scanf("%d",&d);
temp=malloc(d * sizeof(int)); //here
input(d);
conv();
for(x=0;x<d;x++)
{
t=t+temp[x];
}
avg=t/d;
printf("Avarage is %f",avg);
getch();
}
void input(int d)
{
int x=0;
for(x=0;x<d;x++)
{
printf("Input temperature in Celsius for #%d day",x+1);
scanf("%d",&temp[x]);
}
}
void conv()
{
int x=0;
for(x=0;x<d;x++)
{
temp[x]=1.8*temp[x]+32;
}
}
Maybe it's late to answer but...
If you work with small embedded system you might not have malloc and free functions.
So you have to sacrifice memory for 366 * sizeof(your_type), define it statically and use as a circular buffer. Then you can always slice it by number of days you need to calculate an average value.
Of course this makes natural constrains. You can define it by yourself.

Resources