Using two different functions to change variable in main and print - c

So I have to create two functions. In the int main, the program asks to input an x and y value. On the first function, it adds 1 to the x and y value. And on the next function, it prints out the result from that function. And now my problem is that the 2nd function doesn't print out the output from the first function, I do not know what I'm doing wrong, here's my code so far:
#include <stdio.h>
void plusone(int *x,int *y);
void printresult(int *x, int *y);
int main()
{
int x,y;
printf("enter x variable: ");
scanf("%d",&x);
printf("enter y variable: ");
scanf("%d",&y);
plusone(&x,&y);
printf ("%d and %d\n\n",x,y);
printresult(&x,&y);
}
void plusone(int *x,int *y)
{
return *x+1;
}
void printresult(int *x,int *y)
{
printf("the result is: x:%d y:%d",*x,*y);
}
so when I run that program, enter 1 for x and 2 for y, the output is still 1 and 2, but it's supposed to be 2 for x and 2 for y after the plusone function, can I ask what's wrong with my code? Sorry for my english but I hope I explained it well, I am new to C programming

A better answer is that the plusone function is not applying any side-effect on the *x parameter. Here is a plusone function that has a side-effect (actually two--one on each variable passed in):
void plusone(int *x,int *y)
{
*x = *x+1;
*y = *y+1;
}

You are passing a pointer to plusone - that's a good start. However, you are not using that pointer to update the value passed in:
void plusone(int *x,int *y)
{
*x = *x+1;
}
or better
void plusone(int *x,int *y)
{
(*x)++;
}
Now you assign a new value to whatever x is pointing, that is, to the variable x of main.
Note: Since you were returning a value from a function declared void, the compiler should have given you a warning.
Note: although passing by pointer to plusone is necessary, you can pass by value to printresult, because the function does not need to change values of the local variables in main that you pass to it.

void plusone(int *x,int *y)
{
return *x+1;
}
should be
void plusone(int *x,int *y)
{
(*x)++; //or *x+=1; which is the short for *x=*x+1;
}
You cannot return an int for a function that does not return anything (void).But here,I don't think you were attempting to return a variable.You wanted the variable x to be incremented once.So just do that in your program just like I've done above.

You should not return from plusone, this is the right solution
#include <stdio.h>
void plusone(int *x, int *y);
void printresult(int x, int y);
int /* main() returns int */ main()
{
int x, y;
printf("enter x variable: ");
scanf("%d",&x);
printf("enter y variable: ");
scanf("%d",&y);
plusone(&x, &y);
printresult(x, y);
return 0; // main sholud return `int' as you see from it's definition.
}
void
plusone(int *x, int *y)
{
*x += 1;
*y += 1;
}
void printresult(int x, int y)
{
printf("the result is:\n\tx: %d\n\ty: %d\n", x, y);
}
You said,
it adds 1 to the x and y value_
in your plusone function you was passing int *y but never doing anything with it, and int *x but not updating it's value.

plusone is trying to return an int what it's return type is void. And it isn't even trying to change anything (no assignment statement).

If you're trying to manipulate the x and y variables directly, like I think you are, you need to do something like
*x += 1;
*y += 1;
in that function

How about this solution.
void plusone(int *x,int *y)
{
*x += 1;
}
I think your original source will make compile error due to return int in void function

Related

Function Pointer with void* return and void* parameters

I wrote a function pointer that has all void* so that it can be used for any numeric value
int
float
double.
But it is working only for the int addition function
For float and double addition functions, it throws compile time error.
Why is that so ?
If you uncomment the last two printf lines, you would receive error
#include<stdio.h>
int int_add(int x, int y) {
return x + y;
}
float float_add(float x, float y) {
return x + y;
}
double double_add(double x, double y) {
return x + y;
}
void* do_operation(void* (*op)(void*, void*), void* x, void* y) {
return op(x, y);
}
void main(void) {
printf("Sum= %d\n",(int*) do_operation(int_add, 1, 2));
/*printf("Sum= %f\n",(float*) do_operation(float_add, 1.20, 2.50));*/
/*printf("Sum= %lf\n",(double*) do_operation(double_add, 1.20, 2.50));*/
}
void * is a pointer type. You're not passing pointers, you're passing values, so that's not going to compile. It accidentally "works" for int because pointers themselves are represented as integers by most C compilers.
If you pass pointers to int, float, and double instead of the int, float, and double themselves, you will avoid that compiler error. You'd also need to change int_add and friends to take pointers, and you'd have to make sure you dereferenced the pointers before using them. You'll also have to return pointers, which means you'll have to malloc some memory on the heap, because the stack memory assigned to your local variables will be invalid once your function exits. You'll then have to free it all later... in the end, this is going to result in something considerably more complicated than the problem it appears you are trying to solve.
I have to ask why you are trying to do this? C is really not the best language for this type of pattern. I'd suggest just calling the int_add, float_add, etc. functions directly instead of trying to abstract them in this way.
So as per #charles-srstka suggestion I rewrote the code and then it worked as I wanted
#include<stdio.h>
#include<stdlib.h>
int* int_add(int *x, int *y) {
int *c = (int *)malloc(sizeof(int));
*c = *(int*)x + *(int*)y;
return c;
}
float* float_add(float *x, float *y) {
float *c = (float*)malloc(sizeof(float));
*c = *(float*)x + *(float*)y;
return c;
}
void* do_operation(void* (*op)(void*, void*), void* x, void* y) {
return op(x, y);
}
void main(void) {
int a = 1;
int b = 2;
int *c;
c = do_operation(int_add, &a, &b);
printf("%d\n",*c);
free(c);
float x = 1.1;
float y = 2.2;
float *z;
z = do_operation(float_add, &x, &y);
printf("%f\n",*z);
free(z);
}

Pointers in C , understanding the difference

void noOfClients(struct noOfClients *q );
I understand that a pointer's name holds the memory address of a variable.
But, when * comes with a pointer, it represents the content of that location.
In the above line of code, when passing a by reference, we'd say:
void noOfClients( &q);
But why?
Thank you.
* has different meaning when it is used in a variable/argument declaration and when it is used as a pointer dereference operator.
In a variable/argument declaration, it declares the variable/argument to be of a pointer type.
struct noOfClients *q
declares q to be a pointer to a struct noOfClients.
When used in an expression,
*q
dereferences where q points to.
PS
void noOfClients( &q);
is not the right way to call the function. Just use:
noOfClients(&q);
That will work if q is declared as an object.
struct noOfClients q;
noOfClients(&q);
void func(foo *a);
This is a function prototype of a function taking a pointer to a foo. Some people like to write this as
void func(foo* a);
There's no difference, but you might say that the function takes a "foo-pointer", rather than a "pointer to a foo".
a is a foo*
*a is a foo
There is no difference.
because & indicates the address of a particular variable and when you deal with functions so when you pass a variable to the function so you do some changes in that variable, sometimes the reflection of value are not done in that variable but if you pass a variable with its address then reflection will be done properly just try and understand following two codes it will sure help you
without &
#include <stdio.h>
void swap(int, int);
int main()
{
int x, y;
printf("Enter the value of x and y\n");
scanf("%d%d",&x,&y);
printf("Before Swapping\nx = %d\ny = %d\n", x, y);
swap(&x, &y);
printf("After Swapping\nx = %d\ny = %d\n", x, y);
return 0;
}
void swap(int a, int b)
{
int temp;
temp = b;
b = a;
a = temp;
}
with &
#include <stdio.h>
void swap(int*, int*);
int main()
{
int x, y;
printf("Enter the value of x and y\n");
scanf("%d%d",&x,&y);
printf("Before Swapping\nx = %d\ny = %d\n", x, y);
swap(&x, &y);
printf("After Swapping\nx = %d\ny = %d\n", x, y);
return 0;
}
void swap(int *a, int *b)
{
int temp;
temp = *b;
*b = *a;
*a = temp;
}

Swapping variables with a function doesn't affect the call site

A few lessons ago I learned about variables, and got a question in my homework about swapping two numbers - I used a third variable to solve this question.
The solution looked somewhat like this:
#include <stdio.h>
int main(void) {
int x, y;
scanf("%d %d", &x, &y);
// swappring the values
int temp = x;
x = y;
y = temp;
printf("X is now %d and Y is now %d", x, y);
}
Now I'm learning about functions, and I wanted to try and solve the previous question with a helper swap function.
This is the code I've written:
#include <stdio.h>
void swap(int x, int y) {
int temp = x;
x = y;
y = temp;
}
int main(void) {
int a = 3, b = 4;
swap(a, b);
printf("%d %d\n", a, b);
}
I don't know why, but the output is still 3 4 even though I changed the value inside the swap() function.
Why is this happening?
Pass address of x and y as arguments to function. Right now they are local variables, changes are not made to original variables .
Do as follows-
void swap(int *x,int *y){
/* dereference pointers and swap */
int temp = *x;
*x = *y;
*y = temp;
}
And call in main like this -
swap(&x,&y);
What you are doing is passing parameter by value. It means that during the function call, copies of parameters are created. So inside the function you are working on copies of actual variables.
Instead you need to pass it as a reference. Please read more about pass-by-value vs pass-by-reference.
#include <stdio.h>
void swap(int& x,int& y) //Instead of passing by value just pass by reference
{
int temp=x;
x=y;
t=yemp;
}
int main() {
int a=3,b=4;
swap(a,b);
printf("%d %d\n",a,b);
return 0;
}
EDIT:
C does not have references. Above code will work in c++ instead. To make in work in C, just use pointers and de-reference it inside the function.

Changing values in a local scope

Does anyone know of a way I can change the values of variables that are defined locally?
#include <stdio.h>
int change(int x, int y);
int main()
{
int x = 10;
int y = 20;
change(x,y);
printf("x:%d y:%d\n", x, y);
}
int change(int x, int y)
{
x = 20;
y = 30;
return(x);
return(y);
}
I want x and y to print 20 and 30 in main().
I tried returning the values, but that didn't work. Is there another method I might be able to use? I was thinking pointers, but I don't know where to begin.
Use pointers:
void change(int *x, int *y)
{
*x = 20;
*y = 30;
}
and call the function like: change(&x, &y); For readability you may want to use different names than x and y for the change parameters as they are not of the same type as the x and y variables declared in main.
Some options:
1) Pass by refernce: int change(int &x, int &y);
2) Return an array and change current values:
int* temp = new int[2];
temp[0]=x+10;
temp[1]=y+10;
return temp;
3) Return to printf directly:
printf("x:%d y:%d\n", change(x,y)[0], change(x,y)[1]);
yes it's very easy
just pass the parameters by reference to the change function
so instead of
int change(int x, int y) >
int change(int& x, int& y)
and it will works fine

How to return two values from a function? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
returning multiple values from a function
Suppose i have passed two values to a function iCalculate(int x, int y) and this iCalculate returns two values. Those are as follows:-
(x*y)
(x/y)
Now how should i return the above two values at the same time with the same function?
My Approach was:-
int* iCalculate(int x,int y){
int temp[2];
temp[0] = x*y;
temp[1] = x/y;
return temp;
}
returning the address of the first element of a local array has undefined behavior(at least dereferencing it later is).
You may use output parameters, that is, pass two pointers, and set the values inside
void Calculate(int x, int y, int* prod, int* quot)
{
*prod = x*y;
*quot = x/y;
}
usage:
int x = 10,y = 2, prod, quot;
Calculate(x, y, &prod, &quot)
Another thing you could do is pack your data into a struct
typedef struct
{
int prod;
int quot;
} product_and_quot;
product_and_quot Calculate(int x, int y)
{
product_and_quot p = {x*y, x/y};
return p;
}
That won't work, since you're returning a pointer to a temporary array, which will stop existing at function return time.
Instead, define
typedef struct { int first, second; } IntPair;
and return an object of that type.
(This is what the standard library functions div and ldiv do, except that they call the type differently.)
Your approach is wrong, temp is out of scope/ not longer exist when functon iCalculate exit. So you must not return the address of temp. That would be address of out of scope/ no longer exist variable. Accessing that address means undefined behaviour.
You can use this approach:
void iCalculate(int x,int y,int *mult,int *divi){
*mult = x*y;
*divi = x/y;
}
or you can use another approach:
typedef struct{
int mul, divi;
} TResult;
TResult iCalculate(int x,int y){
TResult res;
res.mul = x*y;
res.divi = x/y;
return res;
}
or :
void iCalculate(int x,int y,TResult *res){
res->mul = x*y;
res->divi = x/y;
}
I suggest the first approach. I think it is too silly to create a new struct definition only to wrap 2 unrelated value together.
The way you did is wrong since int temp[2] disappears once the function returns, so the caller has a "dangling" pointer. You have to add static. Another way, likely better, is to let the caller pass where it wants the result be store e.g.
void iCalc(int x, int y, int *rp, int *rq)
{
// check if rp and rq are NULL, if so, returns
*rp = x*y;
*rq = x/y; // y != 0, and this will truncate of course.
}
and the caller will do something like
int res[2];
iCalc(x, y, res, res+1);
or similar.
Your approach was not so wrong you can return the address of the table like this :
int *iCalculate(int x,int y){
int *temp=malloc(sizeof(int)*2);
temp[0]=x*y;
temp[1]=x/y;
return temp;
}
dont forget to free the memory :
int *result;
result=iCalculate(10,7);
printf("%d %d\n",result[0],result[1]);
free(result);

Resources