为什么要使用双指针?或者为什么要使用指针指针?

man*_*nju 247 c pointers

什么应该在C中使用双指针?任何人都可以用一个例子来解释

我所知道的是双指针是指向指针的指针.为什么我需要一个指针指针?

pmg*_*pmg 454

如果你想要一个字符列表(一个单词),你可以使用 char *word

如果你想要一个单词列表(一个句子),你可以使用 char **sentence

如果你想要一个句子列表(一个独白),你可以使用 char ***monologue

如果你想要一个独白列表(传记),你可以使用 char ****biography

如果您想要一份传记列表(生物图书馆),您可以使用 char *****biolibrary

如果你想要一个生物库列表(一个??大声笑),你可以使用 char ******lol

......

是的,我知道这些可能不是最好的数据结构


使用示例非常非常无聊lol

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int wordsinsentence(char **x) {
    int w = 0;
    while (*x) {
        w += 1;
        x++;
    }
    return w;
}

int wordsinmono(char ***x) {
    int w = 0;
    while (*x) {
        w += wordsinsentence(*x);
        x++;
    }
    return w;
}

int wordsinbio(char ****x) {
    int w = 0;
    while (*x) {
        w += wordsinmono(*x);
        x++;
    }
    return w;
}

int wordsinlib(char *****x) {
    int w = 0;
    while (*x) {
        w += wordsinbio(*x);
        x++;
    }
    return w;
}

int wordsinlol(char ******x) {
    int w = 0;
    while (*x) {
        w += wordsinlib(*x);
        x++;
    }
    return w;
}

int main(void) {
    char *word;
    char **sentence;
    char ***monologue;
    char ****biography;
    char *****biolibrary;
    char ******lol;

    //fill data structure
    word = malloc(4 * sizeof *word); // assume it worked
    strcpy(word, "foo");

    sentence = malloc(4 * sizeof *sentence); // assume it worked
    sentence[0] = word;
    sentence[1] = word;
    sentence[2] = word;
    sentence[3] = NULL;

    monologue = malloc(4 * sizeof *monologue); // assume it worked
    monologue[0] = sentence;
    monologue[1] = sentence;
    monologue[2] = sentence;
    monologue[3] = NULL;

    biography = malloc(4 * sizeof *biography); // assume it worked
    biography[0] = monologue;
    biography[1] = monologue;
    biography[2] = monologue;
    biography[3] = NULL;

    biolibrary = malloc(4 * sizeof *biolibrary); // assume it worked
    biolibrary[0] = biography;
    biolibrary[1] = biography;
    biolibrary[2] = biography;
    biolibrary[3] = NULL;

    lol = malloc(4 * sizeof *lol); // assume it worked
    lol[0] = biolibrary;
    lol[1] = biolibrary;
    lol[2] = biolibrary;
    lol[3] = NULL;

    printf("total words in my lol: %d\n", wordsinlol(lol));

    free(lol);
    free(biolibrary);
    free(biography);
    free(monologue);
    free(sentence);
    free(word);
}
Run Code Online (Sandbox Code Playgroud)

输出:

total words in my lol: 243

  • 只是想指出一个`arr [a] [b] [c]`不是一个`*** arr`。指针的指针使用引用的引用,而`arr [a] [b] [c]`作为常规数组以行主顺序存储。 (3认同)

Ash*_*sha 162

一个原因是你想要将传递给函数的指针的值更改为函数参数,为此需要指向指针的指针.

简单地说,使用**时要保留(或保留在变化)的内存分配或分配甚至外面的函数调用.(所以,用双指针arg传递这样的函数.)

这可能不是一个很好的例子,但会告诉你基本用法:

void allocate(int** p)
{
  *p = (int*)malloc(sizeof(int));
}

int main()
{
  int* p = NULL;
  allocate(&p);
  *p = 42;
  free(p);
}
Run Code Online (Sandbox Code Playgroud)

  • 如果分配是`void allocate(int*p)`并且你把它称为`allocate(p)`会有什么不同? (12认同)

Bri*_*nos 78

这是一个简单的答案!!!!

  • 假设你有一个指针,它的值是一个地址.
  • 但现在你要改变那个地址.
  • 你可以通过执行pointer1 = pointer2,而现在指针1将具有指针2的地址.
  • 但!如果你想要一个函数为你做这个,并且你希望结果在函数完成后保持,你需要做一些额外的工作,你需要一个新的指针3只是指向pointer1,并将指针3传递给函数.

  • 这是一个有趣的例子(首先看看输出波纹管,了解!):

#include <stdio.h>

int main()
{

    int c = 1;
    int d = 2;
    int e = 3;
    int * a = &c;
    int * b = &d;
    int * f = &e;
    int ** pp = &a;  // pointer to pointer 'a'

    printf("\n a's value: %x \n", a);
    printf("\n b's value: %x \n", b);
    printf("\n f's value: %x \n", f);
    printf("\n can we change a?, lets see \n");
    printf("\n a = b \n");
    a = b;
    printf("\n a's value is now: %x, same as 'b'... it seems we can, but can we do it in a function? lets see... \n", a);
    printf("\n cant_change(a, f); \n");
    cant_change(a, f);
    printf("\n a's value is now: %x, Doh! same as 'b'...  that function tricked us. \n", a);

    printf("\n NOW! lets see if a pointer to a pointer solution can help us... remember that 'pp' point to 'a' \n");
     printf("\n change(pp, f); \n");
    change(pp, f);
    printf("\n a's value is now: %x, YEAH! same as 'f'...  that function ROCKS!!!. \n", a);
    return 0;
}

void cant_change(int * x, int * z){
    x = z;
    printf("\n ----> value of 'a' is: %x inside function, same as 'f', BUT will it be the same outside of this function? lets see\n", x);
}

void change(int ** x, int * z){
    *x = z;
    printf("\n ----> value of 'a' is: %x inside function, same as 'f', BUT will it be the same outside of this function? lets see\n", *x);
}
Run Code Online (Sandbox Code Playgroud)
  • 这是输出:
 a's value: bf94c204

 b's value: bf94c208 

 f's value: bf94c20c 

 can we change a?, lets see 

 a = b 

 a's value is now: bf94c208, same as 'b'... it seems we can, but can we do it in a function? lets see... 

 cant_change(a, f); 

 ----> value of 'a' is: bf94c20c inside function, same as 'f', BUT will it be the same outside of this function? lets see

 a's value is now: bf94c208, Doh! same as 'b'...  that function tricked us. 

 NOW! lets see if a pointer to a pointer solution can help us... remember that 'pp' point to 'a' 

 change(pp, f); 

 ----> value of 'a' is: bf94c20c inside function, same as 'f', BUT will it be the same outside of this function? lets see

 a's value is now: bf94c20c, YEAH! same as 'f'...  that function ROCKS!!!. 
Run Code Online (Sandbox Code Playgroud)

  • 这是一个很好的答案,确实帮助我想象了双指针的目的和有用性。 (8认同)
  • 很好的答案,只是缺乏解释<code> void cant_change(int*x,int*z)</ code>失败,因为它的'参数只是新的本地作用域指针,同样初始化a和f指针(因此它们不是与a和f)相同. (8认同)

Sil*_*iu 46

添加Asha的响应,如果你使用指向示例下的单个指针(例如alloc1()),你将失去对函数内部分配的内存的引用.

void alloc2(int** p) {
   *p = (int*)malloc(sizeof(int));
   **p = 10;
}

void alloc1(int* p) {
   p = (int*)malloc(sizeof(int));
   *p = 10;
}

int main(){
   int *p = NULL;
   alloc1(p);
   //printf("%d ",*p);//undefined
   alloc2(&p);
   printf("%d ",*p);//will print 10
   free(p);
   return 0;
}
Run Code Online (Sandbox Code Playgroud)

它发生的原因是alloc1指针是按值传入的.因此,当它被重新分配给malloc内部调用的结果时alloc1,更改不属于不同范围内的代码.

  • 不需要(!)在 C 中转换 malloc 的结果。 (3认同)

ziy*_*ang 22

今天我在这篇博文中看到了一个很好的例子,我在下面总结一下.

想象一下,你有一个链表中的节点结构,可能是

typedef struct node
{
    struct node * next;
    ....
} node;
Run Code Online (Sandbox Code Playgroud)

现在,您要实现一个remove_if函数,该函数接受删除条件rm作为参数之一并遍历链表:如果条目满足条件(类似rm(entry)==true),则其节点将从列表中删除.最后,remove_if返回链表的头部(可能与原始头部不同).

你可以写

for (node * prev = NULL, * curr = head; curr != NULL; )
{
    node * const next = curr->next;
    if (rm(curr))
    {
        if (prev)  // the node to be removed is not the head
            prev->next = next;
        else       // remove the head
            head = next;
        free(curr);
    }
    else
        prev = curr;
    curr = next;
}
Run Code Online (Sandbox Code Playgroud)

作为你的for循环.消息是,没有双指针,你必须维护一个prev变量来重新组织指针,并处理两种不同的情况.

但是使用双指针,你实际上可以写

// now head is a double pointer
for (node** curr = head; *curr; )
{
    node * entry = *curr;
    if (rm(entry))
    {
        *curr = entry->next;
        free(entry);
    }
    else
        curr = &entry->next;
}
Run Code Online (Sandbox Code Playgroud)

你现在不需要,prev因为你可以直接修改prev->next指向的内容.

为了使事情更清楚,让我们稍微遵循一下代码.在删除期间:

  1. 如果entry == *head:它将*head (==*curr) = *head->next- head现在指向新标题节点的指针.您可以通过直接将head内容更改为新指针来完成此操作.
  2. if entry != *head:同样,*currprev->next指向的,现在指向entry->next.

无论在哪种情况下,您都可以使用双指针以统一的方式重新组织指针.


Bha*_*hur 21

1.基本概念 -

当您声明如下: -

1. char*ch - (称为字符指针)
- ch包含单个字符的地址.
- (*ch)将取消引用字符的值..

2. char**ch -
'ch'包含一个字符指针数组的地址.(如1)
'*ch'包含单个字符的地址.(请注意,由于声明不同,它与1不同).
(**ch)将取消引用该字符的确切值.

添加更多指针会扩展数据类型的维度,从字符到字符串,再到字符串数组等等......您可以将它与1d,2d,3d矩阵相关联.

因此,指针的使用取决于您如何声明它.

这是一个简单的代码..

int main()
{
    char **p;
    p = (char **)malloc(100);
    p[0] = (char *)"Apple";      // or write *p, points to location of 'A'
    p[1] = (char *)"Banana";     // or write *(p+1), points to location of 'B'

    cout << *p << endl;          //Prints the first pointer location until it finds '\0'
    cout << **p << endl;         //Prints the exact character which is being pointed
    *p++;                        //Increments for the next string
    cout << *p;
}
Run Code Online (Sandbox Code Playgroud)

2.双指针的另一种应用 -
(这也包括通过引用传递)

假设您要从函数更新字符.如果您尝试以下方法: -

void func(char ch)
{
    ch = 'B';
}

int main()
{
    char ptr;
    ptr = 'A';
    printf("%c", ptr);

    func(ptr);
    printf("%c\n", ptr);
}
Run Code Online (Sandbox Code Playgroud)

输出将是AA.这不起作用,因为你有"通过值传递"功能.

正确的方法是 -

void func( char *ptr)        //Passed by Reference
{
    *ptr = 'B';
}

int main()
{
    char *ptr;
    ptr = (char *)malloc(sizeof(char) * 1);
    *ptr = 'A';
    printf("%c\n", *ptr);

    func(ptr);
    printf("%c\n", *ptr);
}
Run Code Online (Sandbox Code Playgroud)

现在扩展此更新字符串而不是字符的要求.
为此,您需要在函数中接收参数作为双指针.

void func(char **str)
{
    strcpy(str, "Second");
}

int main()
{
    char **str;
    // printf("%d\n", sizeof(char));
    *str = (char **)malloc(sizeof(char) * 10);          //Can hold 10 character pointers
    int i = 0;
    for(i=0;i<10;i++)
    {
        str = (char *)malloc(sizeof(char) * 1);         //Each pointer can point to a memory of 1 character.
    }

    strcpy(str, "First");
    printf("%s\n", str);
    func(str);
    printf("%s\n", str);
}
Run Code Online (Sandbox Code Playgroud)

在此示例中,方法需要双指针作为参数来更新字符串的值.


Jas*_*son 15

指针的指针也可以作为内存的"句柄"派上用场,你想要在函数之间传递一个"句柄"来重新定位内存.这基本上意味着函数可以更改句柄变量内指针所指向的内存,并且使用句柄的每个函数或对象都将正确指向新重定位(或分配)的内存.图书馆喜欢用"不透明"的数据类型来做这件事,那就是数据类型你不必担心他们正在做的事情与你所做的事情有关,你只需要绕过"处理器"之间的"句柄".库的函数在该内存上执行某些操作...库函数可以在内部分配和解除分配内存,而无需明确担心内存管理过程或句柄指向的位置.

例如:

#include <stdlib.h>

typedef unsigned char** handle_type;

//some data_structure that the library functions would work with
typedef struct 
{
    int data_a;
    int data_b;
    int data_c;
} LIB_OBJECT;

handle_type lib_create_handle()
{
    //initialize the handle with some memory that points to and array of 10 LIB_OBJECTs
    handle_type handle = malloc(sizeof(handle_type));
    *handle = malloc(sizeof(LIB_OBJECT) * 10);

    return handle;
}

void lib_func_a(handle_type handle) { /*does something with array of LIB_OBJECTs*/ }

void lib_func_b(handle_type handle)
{
    //does something that takes input LIB_OBJECTs and makes more of them, so has to
    //reallocate memory for the new objects that will be created

    //first re-allocate the memory somewhere else with more slots, but don't destroy the
    //currently allocated slots
    *handle = realloc(*handle, sizeof(LIB_OBJECT) * 20);

    //...do some operation on the new memory and return
}

void lib_func_c(handle_type handle) { /*does something else to array of LIB_OBJECTs*/ }

void lib_free_handle(handle_type handle) 
{
    free(*handle);
    free(handle); 
}


int main()
{
    //create a "handle" to some memory that the library functions can use
    handle_type my_handle = lib_create_handle();

    //do something with that memory
    lib_func_a(my_handle);

    //do something else with the handle that will make it point somewhere else
    //but that's invisible to us from the standpoint of the calling the function and
    //working with the handle
    lib_func_b(my_handle); 

    //do something with new memory chunk, but you don't have to think about the fact
    //that the memory has moved under the hood ... it's still pointed to by the "handle"
    lib_func_c(my_handle);

    //deallocate the handle
    lib_free_handle(my_handle);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助,

贾森

  • `unsigned char`是专门使用的,因为我们存储了一个指向二进制数据的指针,它将表示为原始字节.使用`void`将需要在某些时候进行强制转换,并且通常不像所做的那样可读. (4认同)

pla*_*ts1 6

您可能以前见过很多次的简单示例

int main(int argc, char **argv)
Run Code Online (Sandbox Code Playgroud)

在第二个参数中你有它:指向char的指针.

请注意,指针表示法(char* c)和数组表示法(char c[])在函数参数中是可互换的.所以你也可以写char *argv[].换句话说char *argv[],char **argv是可以互换的.

上面所代表的实际上是一个字符序列数组(在启动时给予程序的命令行参数).

有关上述函数签名的更多详细信息,请参阅此答案.

  • *“函数参数中的指针符号(`char * c`)和数组符号(`char c []`)是可互换的” *(并且具有相同的确切含义)。它们是不同的,但是外部函数参数不同。 (2认同)

dry*_*dam 5

字符串是使用双指针的一个很好的例子.字符串本身是一个指针,所以每当你需要指向一个字符串时,你需要一个双指针.


Jef*_*ter 5

例如,您可能要确保释放内存时将指针设置为null。

void safeFree(void** memory) {
    if (*memory) {
        free(*memory);
        *memory = NULL;
    }
}
Run Code Online (Sandbox Code Playgroud)

调用此函数时,将使用指针地址进行调用

void* myMemory = someCrazyFunctionThatAllocatesMemory();
safeFree(&myMemory);
Run Code Online (Sandbox Code Playgroud)

现在myMemory设置为NULL,任何重用它的尝试显然都是错误的。


jon*_*oni 5

聚会有点晚了,但希望这会对某人有所帮助。

在 C 数组中总是在堆栈上分配内存,因此函数不能返回(非静态)数组,因为当执行到达当前块的末尾时,分配在堆栈上的内存会自动释放。当您想要处理二维数组(即矩阵)并实现一些可以更改和返回矩阵的函数时,这真的很烦人。为此,您可以使用指针到指针来实现具有动态分配内存的矩阵:

/* Initializes a matrix */
double** init_matrix(int num_rows, int num_cols){
    // Allocate memory for num_rows float-pointers
    double** A = calloc(num_rows, sizeof(double*));
    // return NULL if the memory couldn't allocated
    if(A == NULL) return NULL;
    // For each double-pointer (row) allocate memory for num_cols floats
    for(int i = 0; i < num_rows; i++){
        A[i] = calloc(num_cols, sizeof(double));
        // return NULL if the memory couldn't allocated
        // and free the already allocated memory
        if(A[i] == NULL){
            for(int j = 0; j < i; j++){
                free(A[j]);
            }
            free(A);
            return NULL;
        }
    }
    return A;
} 
Run Code Online (Sandbox Code Playgroud)

这是一个插图:

double**       double*           double
             -------------       ---------------------------------------------------------
   A ------> |   A[0]    | ----> | A[0][0] | A[0][1] | A[0][2] | ........ | A[0][cols-1] |
             | --------- |       ---------------------------------------------------------
             |   A[1]    | ----> | A[1][0] | A[1][1] | A[1][2] | ........ | A[1][cols-1] |
             | --------- |       ---------------------------------------------------------
             |     .     |                                    .
             |     .     |                                    .
             |     .     |                                    .
             | --------- |       ---------------------------------------------------------
             |   A[i]    | ----> | A[i][0] | A[i][1] | A[i][2] | ........ | A[i][cols-1] |
             | --------- |       ---------------------------------------------------------
             |     .     |                                    .
             |     .     |                                    .
             |     .     |                                    .
             | --------- |       ---------------------------------------------------------
             | A[rows-1] | ----> | A[rows-1][0] | A[rows-1][1] | ... | A[rows-1][cols-1] |
             -------------       ---------------------------------------------------------
Run Code Online (Sandbox Code Playgroud)

双指针到双指针A指向A[0]内存块的第一个元素,其元素是双指针本身。你可以把这些双指针想象成矩阵的行。这就是为什么每个双指针都为 double 类型的 num_cols 元素分配内存的原因。此外A[i]指向第 i 行,即A[i]指向A[i][0]并且这只是第 i 行的内存块的第一个双元素。最后,您可以使用 轻松访问第 i 行和第 j 列中的元素A[i][j]

这是演示用法的完整示例:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

/* Initializes a matrix */
double** init_matrix(int num_rows, int num_cols){
    // Allocate memory for num_rows double-pointers
    double** matrix = calloc(num_rows, sizeof(double*));
    // return NULL if the memory couldn't allocated
    if(matrix == NULL) return NULL;
    // For each double-pointer (row) allocate memory for num_cols
    // doubles
    for(int i = 0; i < num_rows; i++){
        matrix[i] = calloc(num_cols, sizeof(double));
        // return NULL if the memory couldn't allocated
        // and free the already allocated memory
        if(matrix[i] == NULL){
            for(int j = 0; j < i; j++){
                free(matrix[j]);
            }
            free(matrix);
            return NULL;
        }
    }
    return matrix;
}

/* Fills the matrix with random double-numbers between -1 and 1 */
void randn_fill_matrix(double** matrix, int rows, int cols){
    for (int i = 0; i < rows; ++i){
        for (int j = 0; j < cols; ++j){
            matrix[i][j] = (double) rand()/RAND_MAX*2.0-1.0;
        }
    }
}


/* Frees the memory allocated by the matrix */
void free_matrix(double** matrix, int rows, int cols){
    for(int i = 0; i < rows; i++){
        free(matrix[i]);
    }
    free(matrix);
}

/* Outputs the matrix to the console */
void print_matrix(double** matrix, int rows, int cols){
    for(int i = 0; i < rows; i++){
        for(int j = 0; j < cols; j++){
            printf(" %- f ", matrix[i][j]);
        }
        printf("\n");
    }
}


int main(){
    srand(time(NULL));
    int m = 3, n = 3;
    double** A = init_matrix(m, n);
    randn_fill_matrix(A, m, n);
    print_matrix(A, m, n);
    free_matrix(A, m, n);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)