void getnums(int *a, int *b);
int main()
{
int a;
int b;
int c;
getnums(&a,&b);
c = a + b;
printf("a + b = %d\n", c);
return 0;
}
void getnums(int *a, int *b)
{
printf("a:? ");
scanf("%d", a);
printf("b:? ");
scanf("%d", b);
}
Why don't I need ampersands before the a and b in the scanfs? (The code currently works.)
Because scanf takes pointers as its arguments (so that it knows what variable to modify), and a and b are already pointers.
Whenever we scan some input it needs a memory location(i.e. address) to store that value, for simple variables we have to use & - ampersand - to provide that address.
Here, in function getnums, a and b are pointers so they will already contain address, so no need to write & to give the address.
Related
I just started learning, I didn't understand the book, so I asked for advice.
I am a beginner and don't have a good English.
Function: Combine two two-digit positive integers A and B to form an integer in C
Middle. The method of merging is: the ten digits and single digits of the A number are placed on the thousand and ten digits of the C number, and the ten and single digits of the B number are placed on the single and hundred digits of the C number.
For example: when a=45, b=12. After calling this function, c=4251.
Here is my code
#include <stdio.h>
void fun(int a, int b, long *c);
int main()
{
int a,b;
long c;
int state = 1;
printf("Enter a: ");
printf("(q to quit)");
while( scanf("%d",&a)==state)
{
printf("Enter b: ");
printf("(q to quit)");
while( scanf("%d",&b)==state)
{
fun(a, b, &c);
printf("The result is: %ld\n", c);
}
}
return 0;
}
void fun(int a, int b, long *c)
{
/**********Program**********/
*c = 100*(a%100)+b%100;
/********** End **********/
}
I tried removing the * and found that the result was 16. It is wrong but not know why
The parameter long *c means c is an address of a variable (in this case the variable in main() is called c and you need to call the function like this fun(a, b, &c)).
When you want to update the value stored at that address c the syntax is *c = .... If you do c = ... you are updating the address of the variable which has no external effect.
Alternatively, you could change your function to return a value and the call would then look like this:
c = fun(a, b);
and the function would be:
int fun(int a, int b) {
return 100*(a%100)+b%100;
}
I'm working on my intro C course assignment and I'm tasked with the following...
Write code for a function that receives two parameters (a,and b) by value and has two more parameters (c and d) by reference. All parameters are double.
From main, use scanf to get two numbers, then call the function, and then display both returned values to the output in a printf statement.
The function works by assigning (a/b) to c and assigning (a*b) to d.
While my knowledge is basic, I believe I understand the gists
In main
//first and second double hold the scanf inputs
double first;
double second;
//unsure here - to reference c and d as parameters in the function, do I simply declare unfilled double variables here?
double *c;
double *d;
printf("Enter your first number\n");
scanf("%f\n", &first);
printf("Enter your second number\n");
scanf("%d\n", &second);
//call the function, first and second by value, &c / &d by reference - correct?
pointerIntro(first, second, &c, &d);
For the function...
float myFunction(double a, double b, double *c, double *d)
{
c = a/b;
d = a*b;
//printf statements
}
I apologize if the flow of this question is messy but its part of the process for me :P
So, for my formal questions
1. is it correct to initiate two double pointer variables (*c & *d) in main to be passed as reference in the function?
2. Am I right to call the function with the reference pointers by saying &c / &d?
3. Any other critiques of this questioning?
Variables 'c' and 'd' don't have to be pointers to pass them by reference. So you have two cases:
When you define 'c' and 'd' as pointers in main function you will pass them to function like this: pointerIntro(first, second, c, d); because they are already pointers and you don't need to send their reference, you just send them.
If you define 'c' and 'd' just as double variables double c, d; you will send them to the function by reference using '&' symbol like this: pointerIntro(first, second, &c, &d);.
Then in your function to actually set the values of 'c' and 'd' you will need to dereference the pointer to them like this: *c = a/b; *d = a*b;.
If you are not familiar you can check what dereferencing the pointer means here: What does "dereferencing" a pointer mean?
Code that should work:
#include <stdio.h>
void myFunction(double a, double b, double *c, double *d)
{
*c = a / b;
*d = a * b;
}
int main(void)
{
double a, b, c, d;
scanf("%lf", &a);
scanf("%lf", &b);
myFunction(a, b, &c, &d);
printf("%lf %lf", c, d);
}
You need to dereference c and d to assign them in myFunction():
*c = a/b;
*d = a*b;
Moreover from main, you need to create instances to which c and d refer to:
double c;
double d;
(you had created unitialised pointers with no instances).
Then in the the call:
pointerIntro(first, second, &c, &d);
The & address-of operator creates the reference arguments, referring to c and d in main().
It might be useful not to use the same symbol names c and d in main() and myFunction() to make it clearer what they are. For example:
void myFunction(double a, double b, double* cptr, double* dptr )
{
*cptr = a/b;
*dptr = a*b;
}
Note also, a function that returns nothing should be declared void.
A pointer is simply a normal variable that holds the address of something else as its value. In other words, a pointer points to the address where something else can be found. Where you normally think of a variable holding an immediate values, such as int a = 40;, a pointer (e.g. int *p = &a;) would simply hold the address where 40 is stored in memory.
If you need to access the value stored at the memory address pointed to by p, you dereference p using the unary '*' operator, e.g. int j = *p; will initialize j = 40).
If you want to obtain a variables address in memory, you use the unary '&' (address of) operator. If you need to pass a variable as a pointer, you simply provide the address of the variable as a parameter.
In your case that boils down to writing your function similar to:
void multdiv (double a, double b, double *c, double *d)
{
*c = a / b;
*d = a * b;
}
(note: you should ensure b != 0 before dividing a / b -- that is left to you)
In order to provide storage for the values you will take as input as well as the values you want to hold the results of the multiplication and division, you need four double values, e.g.
int main (void) {
double a, b, c, d; /* your doubles */
You then need to prompt the user for input and validate the user input by checking the return of the input function used, e.g.
fputs ("enter two double values: ", stdout); /* prompt */
fflush (stdout); /* flush stream (optional but recommended) */
if (scanf ("%lf %lf", &a, &b) != 2) { /* validate EVERY input */
fputs ("error: invalid double values.\n", stderr);
return 1;
}
(bonus: Why is the '&' used before a and b with scanf above? See first full paragraph under DESCRIPTION in man 3 scanf)
All that remains is to call your function to perform the calculations and output the results, e.g.:
multdiv (a, b, &c, &d); /* calculate c, d */
printf ("\nc = a / b => %.2f\nd = a * b => %.2f\n", c, d);
(note: as explained above the address of operator is used to pass the address of c and d as parameters)
Putting it altogether you could do:
#include <stdio.h>
void multdiv (double a, double b, double *c, double *d)
{
*c = a / b;
*d = a * b;
}
int main (void) {
double a, b, c, d; /* your doubles */
fputs ("enter two double values: ", stdout); /* prompt */
fflush (stdout); /* flush stream (optional but recommended) */
if (scanf ("%lf %lf", &a, &b) != 2) { /* validate EVERY input */
fputs ("error: invalid double values.\n", stderr);
return 1;
}
multdiv (a, b, &c, &d); /* calculate c, d */
printf ("\nc = a / b => %.2f\nd = a * b => %.2f\n", c, d);
return 0;
}
Example Use/Output
$ ./bin/multdivbyptrs
enter two double values: 4.0 2.0
c = a / b => 2.00
d = a * b => 8.00
Look things over and let me know if you have questions. Once you digest that a pointer is simply a normal variable that holds the address where something else is stored as its value -- things will start to fall into place. No magic..
It is perfectly valid. You can initialize and pass any number of pointer variables with their reference.
This is also valid..when you pass the variable address, you should store it into a pointers
you have to do some changes in your code,
You can assign directly a/b and a*b pointer variables *c & *d
Then you have to read double number with %lf format argument.
#include <stdio.h>
#include <string.h>
void myFunction(double a, double b, double *c, double *d)
{
*c = a/b; //change
*d = a*b; //change
printf("%lf %lf",*c,*d);
return;
//printf statements
}
int main()
{
//first and second double hold the scanf inputs
double first;
double second;
//unsure here - to reference c and d as parameters in the function, do I simply declare unfilled double variables here?
double *c;
double *d;
printf("Enter your first number\n");
scanf("%lf", &first); //change
printf("Enter your second number\n");
scanf("%lf", &second); //change
//call the function, first and second by value, &c / &d by reference - correct?
myFunction(first, second, &c,&d);
}
Here is the correct way to do it. The func() method
void func(double x,double y,double *z,double *w){
printf("pass by value = %lf, %lf",x,y);
printf("pass by reference = %lf, %lf",*z,*w);
}
The main() method
int main(void){
double first,second,val1,val2;
val1=3.1;
val2=6.3;
printf("Enter your first number\n");
scanf("%lf", &first);
printf("Enter your second number\n");
scanf("%lf", &second);
func(first,second,&val1,&val2);
}
I am a currently learning C and am stuck on a problem I was assigned.
I have to create a function with a parameter of a int pointer, where the user can input an int, and then print out the int in the main method. Currently, I am able to input data and print it out properly within the method itself. However, when the data passes to the main function, it always prints "32766". How can I approach this problem? Thanks for your help.
int main(void) {
int a;
funct2(&a);
printf("Int is %d", a);
}
void funct2(int *a){
int d;
printf("Enter an Integer:: ");
scanf("%d", &d);
printf("%d\n", d);
a = &d;
}
You wrote a = &d; to try to return your integer via pointer. Unfortunately that sets a in funct2 to point to d instead. What you want is *a = d;.
I want to Prompt the user to enter 3 numbers. Then, swap the first number with the second one, the second number with the third and the third with the first by calling a function called "swap".
Functions in C cannot return more than one value so I decided to create a structure with pointers that I will later use in my function. Then, I created three-pointers that will store the address of each one of the numbers so I can dereference to these numbers in my function (as shown below)
Number.pa = *ppb;
Number.pb = *ppc;
Number.pc = *ppa;
Here's my code:
#include <stdio.h>
void swap(); // a = b, b = c, c = a
struct Numbers {
int *pa, *pb, *pc;
} ;
int main(void) {
struct Numbers Number; // Structure to hold the values of the three variables.
int a, b, c;
int *ppa, *ppb, *ppc;
printf("\n Please enter three integer numbers: ");
scanf("%d%d%d", &a, &b, &c);
ppa = &a; ppb = &b; ppc = &c;
swap(a, b, c, Number, *ppa, *ppb, *ppc);
printf("\n %d \t %d \t %d \n", Number.pa, Number.pb, Number.pc);
}
void swap(int a, int b, int c, struct Numbers Number, int *ppa, int *ppb, int *ppc) {
Number.pa = *ppb;
Number.pb = *ppc;
Number.pc = *ppa;
} ;
Most of the arguments to your swap function are either pointless or the work of sheer guessing (or both). The assignment effectively wants you to "rotate" values from a through c. So do that, and only that.
#include <stdio.h>
void swap(int *pa, int *pb, int *pc);
int main()
{
int a, b, c;
printf("\n Please enter three integer numbers: ");
if (scanf("%d %d %d", &a, &b, &c) == 3)
{
swap(&a, &b, &c);
printf("%d %d %d \n", a, b, c);
}
return 0;
}
void swap(int *pa, int *pb, int *pc)
{
int tmp = *pa;
*pa = *pb;
*pb = *pc;
*pc = tmp;
}
Stop reading more into an assignment than is there. If it sounds simple, it probably is. The warning was due to passing the value of dereferenced pointers to int (so int values) to a function expecting int pointers; not int values. As you can see, you don't need to do any of that (and didn't in the first place).
Hii ,
I have written the following code to improve it for the higher datastructures .
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
int display(int *a , int *b , int *c)
{
a[0] = b;
a[1] = c;
printf("\n%d %d",a[0],a[1]); ------- point 1
printf("\n %d %d",*(a[0]),*(a[1])); ------- point 2
return 1;
}
int main()
{
int *a[5];
int b,c;
scanf("%d %d",&b,&c);
printf("%d %d",b,c);
display(a,&b,&c);
getchar();
}
I get the addresses in point 1 , but i dont get the values in point 2....What have i done wrong ... If my program itself is wrong , please jus give me a sample code that can dereference an array of pointers to get the value pointed by the element of array...
This code shouldn't compile. The signature for display should be int display(int **a , int *b , int *c), because a is a pointer to int* (remember that arrays degrade to pointers). Then, you need to write printf("\n%d %d",*a[0],*a[1]) to dereference the pointers in the array.
#include <stdio.h>
int display(int** a, int* b, int* c)
{
// store the value of b and c on array a
a[0] = b;
a[1] = c;
//print the memory addresses stored in hex format
printf("0x%x 0x%x\n", (int)a[0], (int)a[1]);
//print the values
printf("%d %d\n", *a[0], *a[1]);
return 1;
}
int main()
{
int* a[5];
int b,c;
scanf("%d %d",&b,&c);
printf("%d %d\n",b,c);
display(a,&b,&c);
getchar();
return 0;
}
The signature of display() indicates that a is a pointer. In theory, this might work in C, but gcc gave me an error. What you want to tell the compiler is that you want an array of pointers. I accomplished this with int **a in the function signature. The code below shows how I did this. Also, I cleaned it up a bit, since some of your includes aren't needed, the pointers should be printed as unsigned, display would probably be better as a void, having the "\n" at the beginning of the line was irritating in that the last line of output ended up on my prompt line, and the getchar() serves no real purpose here.
#include<stdio.h>
void display(int **a , int *b , int *c)
{
a[0] = b;
a[1] = c;
printf("%u %u\n", a[0], a[1]);
printf("%d %d\n", *a[0], *a[1]);
}
int main(void)
{
int *a[5];
int b,c;
printf("Enter two integers: ");
scanf("%d %d",&b,&c);
printf("%d %d\n",b,c);
display(a,&b,&c);
}
You want store addresses (pointers) in the vector a. Define your function to accept a vector of pointers:
int display(int *a , int *b , int *c)
This has the advantage that the compiler compiles the code.
Or better: use names that help to remember what you mean.