I have created a struct in C with three members of type int.
I want to use a function to compute the value of the member C by adding the values a and b as shown in my code.
#include <stdio.h>
typedef struct nums
{
int a;
int b;
int c;
} number;
void add (number one);
int main (void)
{
number start = {.c = 3, .b = 4};
add (start);
printf("the sum is %d \n", start.c);
return (0);
}
void add (number one)
{
one.c = one.a one.b;
}
When I run the code, I get the value of c as 3 instead of 7. How can I solve this problem?
CodePudding user response:
Pass argument as a pointer
#include <stdio.h>
typedef struct nums
{
int a;
int b;
int c;
} number;
void add (number *pOne);
int main (void)
{
number start = {.a = 3, .b = 4, .c = 0};
add (&start);
printf("the sum is %d \n", start.c);
return (0);
}
void add (number *pOne)
{
pOne->c = pOne->a pOne->b;
}
WHY POINTERS?
You pass the address of start
as a pointer to add
so that you can update start
from within add(...)
. Otherwise, add
would update a copy of start
stored on the stack that gets popped off on the return of add
.
CodePudding user response:
Basically in C, if you pass a variable to a function, first the value of the variable is copied and then the function receives it.
So add
function modifies the copy, not original one.
If you want to modify the original one in another function, you should pass the address of a variable.
Addresses are also copied when passed, but it's not a problem because the destination isn't copied.
#include <stdio.h>
typedef struct tagNumber {
int a;
int b;
int c;
} Number;
void add(Number* one) {
one->c = one->a one->b;
}
int main() {
Number start = { .c=3, .b=4 };
add(&start);
printf("the sum is %d\n", start.c);
return 0;
}
CodePudding user response:
Try the code below:
#include <stdio.h>
int main(){
int a, b, c;
printf("Enter 2 numbers: ");
scanf("%d %d", &a, &b);
c = a b;
printf("%d %d = %d", a, b, c);
return 0;
}