什么是内部指针变量?

3

我知道指针是什么,但我不知道内部指针变量是什么。有人知道它们是什么吗?我最近在一个很流行的梗中看到了这个概念,但我在网上找不到一个合理的解释。

2个回答

7

2
开玩笑的话不说,命令。
int *parr = arr;

可以理解为:

整数指针命名为parr,被设置为arr整数数组中第一个元素的内存地址

或者,另一种说法:

整数指针命名为parr,被设置为变量arr的内部指针

在这个命令中,arr是一个整数数组,例如:

int arr[] = {10, 20, 30, 40};

当你使用这个语法时,你告诉parr存储arr的第一个数组元素(arr[0])的内存地址。我们称这个内存地址为内部指针变量。所有的复合数据类型(例如数组、结构等)都有自己的内部指针,它总是指向其第一个元素的内存地址。需要注意的是,对于字符串来说,它们在C中被表示为char数组,因此也是一种复合数据类型。这个语法等同于int *parr = &arr[0],但更加简洁,因此更常用。当编译器使用变量的内部指针时,我们经常说"变量衰变为指向其第一个元素的指针"。另一方面,如果i是一个单个的int,我们不能写int *p = i,因为它是一个原始数据类型,因此没有内部指针变量。
作为一个简单的例子,看看这段代码:
#include <stdio.h>

int main() {
    int i[] = {10, 20, 30, 40};
    int *pi = i; // pi points to the internal pointer of the variable `i`, that is, the address of its first array element, 10.
    int d = 5;
    // int *pd = d; // you cannot do it as `d` has no internal since it is a primitive data type

    printf("The internal pointer of the int array is                      : %p\n"
           "The address of the first int array element is                 : %p\n"
           "The stored value (.i.e., the memory address) of the pointer is: %p\n",
           (void*)i, (void*)&i[0], (void*)pi);
    return 0;
}

它将输出:
The internal pointer of the int array is                      : 0x7ffd2cfad750
The address of the first int array element is                 : 0x7ffd2cfad750
The stored value (.i.e., the memory address) of the pointer is: 0x7ffd2cfad750

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接