当您可以直接将变量作为指针指向时,为什么要在 C 中创建指针?

Why create a pointer in C when you can just point directly to the variable as a pointer?

我正在学习 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();
}

没错,您不需要额外的指针对象。

您的程序在行为上等同于:

int x;
scanf("%d", &x);
printf("%d\n", x);
getchar();

示例中额外指针的使用可能是出于教学原因:解释如何声明和使用指针。