多层指针解引用的用途是什么?

27 浏览
0 Comments

多层指针解引用的用途是什么?

在任何语言中,什么情况下使用指针需要使用超过一个指针,比如三级指针?什么情况下使用三级指针比仅使用常规指针更有意义?

例如:

char  * * *ptr;

而不是

char *ptr;

admin 更改状态以发布 2023年5月23日
0
0 Comments

如果你在C中使用“对象”,你可能有这样的东西:

struct customer {
    char *name;
    char *address;
    int id;
} typedef Customer;

如果你想创建一个对象,你会做这样的事情:

Customer *customer = malloc(sizeof Customer);
// Initialise state.

这里我们使用指向struct的指针,因为struct参数是按值传递的,我们需要使用一个对象。(另外:Objective-C是C的面向对象封装语言,在内部但可见地使用指向struct的指针。)

如果我需要存储多个对象,我会使用一个数组:

Customer **customers = malloc(sizeof(Customer *) * 10);
int customerCount = 0;

由于C中的数组变量指向第一个项目,所以我再次使用指针。现在我有双重指针。

但现在想象一下,我有一个函数,它过滤数组并返回一个新的数组。但是想象一下,它不能通过返回机制返回,因为它必须返回一个错误代码——我的函数访问一个数据库。我需要通过引用参数来做。这是我的函数签名:

int filterRegisteredCustomers(Customer **unfilteredCustomers, Customer ***filteredCustomers, int unfilteredCount, int *filteredCount);

该函数采用一个客户数组,并返回客户数组的引用(这些客户是指向struct的指针)。它还需要客户数量,并返回过滤后的客户数量(再次是通过引用参数)。

我可以这样调用它:

Customer **result, int n = 0;
int errorCode = filterRegisteredCustomers(customers, &result, customerCount, &n);

我还可以想象更多的情况……这一个没有使用typedef

int fetchCustomerMatrix(struct customer ****outMatrix, int *rows, int *columns);

显然,如果我留下这个的话,我将成为一个可怕和/或残忍的开发人员。所以,使用:

typedef Customer *CustomerArray;
typedef CustomerArray *CustomerMatrix;

我只需要这样做:

int fetchCustomerMatrix(CustomerMatrix *outMatrix, int *rows, int *columns);

如果你的应用程序在你使用每个级别的矩阵的酒店中使用,你可能需要一个数组来存储矩阵:

int fetchHotel(struct customer *****hotel, int *rows, int *columns, int *levels);

或者只需要这个:

typedef CustomerMatrix *Hotel;
int fetchHotel(Hotel *hotel, int *rows, int *columns, int *levels);

别让我开始琢磨一个酒店数组:

int fetchHotels(struct customer ******hotels, int *rows, int *columns, int *levels, int *hotels);

…排列成一个矩阵(某种大型酒店公司?):

int fetchHotelMatrix(struct customer *******hotelMatrix, int *rows, int *columns, int *levels, int *hotelRows, int *hotelColumns);

我想说的是,你可以想象出多个间接引用的疯狂应用程序。只要确保使用typedef如果多指针是一个好主意,并且你决定使用它们。

(这篇帖子算不算七星级开发人员的申请?)

0
0 Comments

每个星号应该被解读为“由指针指向的字符”,因此

char *foo;

是“由指针foo指向的字符”。然而,

char *** foo;

是“由指针指向的指针指向的指针指向的字符,由指针foo指向”。因此foo是一个指针。在那个地址上是第二个指针。在那个指向的地址上是第三个指针。解引用第三个指针将产生一个字符。如果只有这些,很难为此提出很多论据。

然而,仍然有可能做一些有用的工作。想象一下,我们正在编写一个替代bash或其他进程控制程序的程序。我们希望以面向对象的方式管理进程的调用...

struct invocation {
    char* command; // command to invoke the subprocess
    char* path; // path to executable
    char** env; // environment variables passed to the subprocess
    ...
}

但我们想做一些花哨的事情。我们想有一种方法来浏览每个子进程所看到的所有不同的环境变量集。为此,我们将每个调用实例中的env成员收集到一个数组env_list中,并将其传递给处理它的函数:

void browse_env(size_t envc, char*** env_list);

0