Good afternoon Luiz,
This is because in function func1 (int x)
you are passing the value of x, not the reference of x, so the changes of the value of x are made only within the function.
If you play a printf()
within the funct1
you will see that it will give 999.
this does not occur in the case of funct2
because it is a vector, the value of v
(no reference) is already the memory address of element 0 of the vector.
An example of this is when we work with strings in C, we do not use the &
in the scanf()
because the variable already stores the address of the first element.
Solution:
If you want to keep the same format of the function, that is, you do not want to pass as a parameter a pointer to change the value of x, you can modify your code to x receive the result of the function
Code:
#include <stdio.h>
int func1 (int x) {
x = x * 9;
}
void func2 (int v[]) {
v[0] = 9 * v[0];
}
int main (void) {
int x, v[2];
x = 111;
x = func1 (x);
printf ("x: %d\n", x);
v[0] = 111;
func2 (v);
printf ("v[0]: %d\n", v[0]);
return 0;
}
Already in case you want to change the function to pass x
as a parameter, it will look like this:
#include <stdio.h>
int func1 (int *x) {
*x = *x * 9;
}
void func2 (int v[]) {
v[0] = 9 * v[0];
}
int main (void) {
int x = 111, v[2];
func1 (&x);
printf ("x: %d\n", x);
v[0] = 111;
func2 (v);
printf ("v[0]: %d\n", v[0]);
return 0;
}
Where *x
refers to the content of the variable x
.
I don’t know if it’s clear, but I’ll edit the answer if there’s any doubt.
I hope I’ve helped,
Hugs!
If you want to edit your question by adding the piece of code where x passes by parameter and not value.
– WhoisMatt
The same second I sent you edited, good!
– WhoisMatt
Good afternoon H. Lima!! perfect the answer, has cleared up a lot of things here! thank you very much!!
– Luiz Augusto
I’m happy to help! Good luck in studies :D
– H.Lima