C 如果p是指向int的指针,那么在哪里使用&p

C 如果p是指向int的指针,那么在哪里使用&p,c,pointers,C,Pointers,在下面的代码中,p是指向int的指针。很明显,p指向i的地址。通过我的研究,我知道&p指向指针p的地址。但我不明白你为什么需要单独的地址。你什么时候会使用&p int main() { int i = 3, *p = &i; printf("%p",&p); printf("%p",p); return 0; } 如果p是指向int的指针,那么 如果要使用指针到指针,请使用单个指针的地址将其指定给指针到指针 只需要指出,指针也是一种数据类型,它存

在下面的代码中,p是指向int的指针。很明显,p指向i的地址。通过我的研究,我知道&p指向指针p的地址。但我不明白你为什么需要单独的地址。你什么时候会使用&p

int main() {
    int i = 3, *p = &i;
    printf("%p",&p);
    printf("%p",p);
    return 0;
}
如果p是指向int的指针,那么

如果要使用指针到指针,请使用单个指针的地址将其指定给指针到指针

只需要指出,指针也是一种数据类型,它存储在内存位置,并保存一个有效的内存位置作为其值。存储此有效内存位置的地址由&p给出

您的printf也需要修复。%p期望无效*

一个简单的例子:

int nochange(int *c, int *val)
{
    c = val; // Changes local pointer c to point to val
             // Note that C passes copies of the arguments, not actual references.
}
int do_change(int **c, int *val)
{
    *c = val; // Accesses the real pointer c at its real location and makes
              // that one point to val
              // Even though c is a pointer-to-pointer copy, its value is 
              // copied too, and the value is the address of the real c
}

int main()
{
    int a = 1;
    int b = 2;
    int *c = &a; // A pointer is also a datatype that resides in memory

    printf("%d\n", *c); // Will print 1
    nochange(c, &b);
    printf("%d\n", *c); // Will print 1
    do_change(&c, &b);
    printf("%d\n", *c); // Will print 2 because c now points to b
}
我有一个类似的答案,这里有一个关于指针与指针对指针的详细信息:

但我不明白你为什么需要单独的地址

不需要,但存在运算符的地址,因此可以获取指针的地址,这就是

printf("%p\n", &p);
他正在印刷

你什么时候会使用&p

有可能是有用的,例如,你需要传递一个指针,这个函数可以被重新分配到函数中,你可以做这样的事情

int allocateIntegerArray(int **pointerToPointer, size_t someSize)
{
    if (pointerToPointer == NULL)
        return 0;
    *pointerToPointer = malloc(someSize * sizeof(int));

    return (*pointerToPointer != NULL);
}
然后你可以用下面的方法使用这个函数

int *pointer;

if (allocateIntergerArray(&pointer, 10) == 0)
{
    fprintf(stderr, "Error, cannot allocate integer array\n");
    /* do some extra cleanup or recover from this error, or exit() */
    exit(0);
}
指针本身也是变量,因此它们需要存储在某个地方,因此指针的地址告诉您指针存储在哪里,它的值告诉您指针指向哪里


通过知道它的存储位置,您可以执行上述操作。

为什么需要单独的地址变量p驻留在内存中,因此它有一个地址,它的定义是驻留在内存中的内容。@CashCow此链接有许多很好的答案,表示有void*很好,而打印指针标准表示p void*指针参数以十六进制打印,就像由%x或%lx打印一样。它应该是指向void的指针。在这种情况下不要使用术语double pointer。它并不意味着指针指向指针。这意味着双指针。我认为有人投了反对票,因为这不是问题,我认为OP知道这一点。还有,你什么时候会使用&p,我把它理解为指针的一般问题。我的回答给出了一个完美的例子,说明了何时使用它。我只是假设,如果作者知道这一点,他就不需要首先问这个问题。不过我可能误解了。
int allocateIntegerArray(int **pointerToPointer, size_t someSize)
{
    if (pointerToPointer == NULL)
        return 0;
    *pointerToPointer = malloc(someSize * sizeof(int));

    return (*pointerToPointer != NULL);
}
int *pointer;

if (allocateIntergerArray(&pointer, 10) == 0)
{
    fprintf(stderr, "Error, cannot allocate integer array\n");
    /* do some extra cleanup or recover from this error, or exit() */
    exit(0);
}