[英]scanning values using pointers by passing memory address
我是一名刚开始使用C语言学习编程的学生。我现在正在学习指针,并且试图使用指针扫描函数中的值,但是我一直在出错。 我不知道为什么。谢谢您的回答。
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);
}
我为您提供解决方案,您的功能有误。 函数scanf()
需要变量的地址而不是变量的值。
您的代码:
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
}
您必须将变量传递到scanf()
地址。
因此,您的功能应为:
void inputValue(int * inputPtr)
{
printf("ENTER:");
scanf("%d", inputPtr);
}
如果您有整数变量,并且想要阅读它:
int n;
scanf("%d", &n); //you have to pass address of n
但是,如果您有指向变量的指针:
int n;
int * ptr = &n;
scanf("%d", ptr); //address of n -> it is pointing to n
但是,如果您编写* ptr,则表示变量的值指向:
int n;
int * ptr = &n;
scanf("%d", *ptr); //value of n - wrong
它不是传递变量的地址,而是传递其值。 所以这是一样的:
int n;
scanf("%d", n); //value of n - wrong
简单的说明指针:
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
当我们有使用指针的函数时:
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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.