Reputation: 37
I am trying to pass a variable into a function and change its global value but it does not work. Here is the simplified code:
int main()
{
int *Num = malloc (sizeof (int));
ChangeValue(&Num);
printf("Number is %i\n", Num);
}
int ChangeValue(int *temp)
{
*temp = 10
}
The error message is:
expected 'int *' but argument is of type 'int **'
I tried to change the function to int ChangeValue(int **temp) but received the following error:
warning: assignment makes pointer from integer without a cast.
Any suggestions?
Upvotes: 0
Views: 57
Reputation: 317
Variable Num
is a pointer to an int (int*
). Function ChangeValue(int*)
takes a pointer to an int (int*
). However, you are passing a pointer to Num
(int**
) to it.
Short answer: remove &
before Num
in ChangeValue(&Num);
Long answer: You seem to have a problem understanding how pointers work, you might want to read more about this before going further.
Upvotes: 2
Reputation: 164799
int *Num
means Num
is of type int *
. Since it's already an integer pointer, there's no need to take its address again when you pass it to your function that takes an int *
.
ChangeValue(Num);
OTOH, since it is a pointer you will have to dereference it to use it as an integer, like with printf
.
printf("Number is %i\n", *Num);
Upvotes: 3