I am a student just started to learn programming using C. I am now learning pointers and I am trying to scan the value in function using pointers.But I keep getting error. I do not know why.Thanks for your answers.
void inputValue(int *numptr);
int main()
{
int input;
inputValue(&input);
printf("%d\n", input);
return 0;
}
void inputValue(int *inputptr)
{
printf("Enter the value");
scanf_s("%d", *inputptr);
}
I have solution for you, your function is wrong. Function scanf()
needs address of variable not value of variable.
Your code:
void inputValue(int *numptr);
int main()
{
int input;
inputValue(&input);
printf("%d\n", input);
return 0;
}
void inputValue(int *inputptr)
{
printf("Enter the value");
scanf_s("%d", *inputptr); // this is the problem
}
You have to pass into scanf()
address of variable.
So, your function should be:
void inputValue(int * inputPtr)
{
printf("ENTER:");
scanf("%d", inputPtr);
}
If you have integer variable and you want to read to it:
int n;
scanf("%d", &n); //you have to pass address of n
But if you have pointer to variable:
int n;
int * ptr = &n;
scanf("%d", ptr); //address of n -> it is pointing to n
But if you write *ptr it means value of variable it's pointing to:
int n;
int * ptr = &n;
scanf("%d", *ptr); //value of n - wrong
It is not passing address of variable but its value. So this is same:
int n;
scanf("%d", n); //value of n - wrong
Simple explanation pointers:
int n;
int * ptr = &n;
&n -> address of n
n -> value of n
ptr -> address of n
*ptr -> value of n
&ptr -> address of pointer
And when we have function working with pointers:
void setval(int*, int);
void main(void)
{
int n=54;
setval(&n, 5); // passing address of n
// now n=5
}
void setval(int * mem, int val)
{
* mem = val; // it sets value at address mem to val
// so it sets value of n to 5
// if we passed only n not &n
// it would mean address of value in n - if n would be 5 it's like we
// passed address in memory at 0x5
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.