dcv*_*cvl 0 c pointers idiomatic
我正在学习C并且遇到了一个例子,它似乎创造了一个不必要的步骤,但我又是新手.
他创建了一个变量,然后是一个指向该变量的专用指针.我的理解是你可以简单地在变量前加一个*,它将作为指向它的指针......那么为什么要使用另一行代码来创建指针?具体来说,我在谈论为什么他创建指针"*p"只是为了引用"x"而不是说*x指向它.以下是示例代码:
#include <stdio.h>
int main()
{
int x; /* A normal integer*/
int *p; /* A pointer to an integer ("*p" is an integer, so p
must be a pointer to an integer) */
p = &x; /* Read it, "assign the address of x to p" */
scanf( "%d", &x ); /* Put a value in x, we could also use p here */
printf( "%d\n", *p ); /* Note the use of the * to get the value */
getchar();
}
Run Code Online (Sandbox Code Playgroud)
没错,你不需要额外的指针对象.
你的程序在行为上等同于:
int x;
scanf("%d", &x);
printf("%d\n", x);
getchar();
Run Code Online (Sandbox Code Playgroud)
在示例中使用额外指针可能是出于教学原因:解释如何声明和使用指针.