需要指向指针的指针 [英] Need of Pointer to pointer

查看:37
本文介绍了需要指向指针的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

存储指针地址需要什么?

What is necessary for storing the address of a pointer?

  int a = 2;
  int *p = &a;
  int **q = &p;

有什么实际用途吗?实时应用.

Any practical use? Real time applications.

推荐答案

在 C 中,您可以传递对象的值"或地址".如果您在函数调用中传递值,则在函数中所做的更改不会反映在调用位置.并且为了反映变化,你需要传递对象的地址,例如:

In C you can either pass "value" or "address" of an object. If you pass value in function call, then changes made in the function don't reflect at calling place. And to reflect changes, you need to pass address of the object, for example:

void insert(node* head){
   head->data = 10;    // address(or head) is still same 
}

对象我指的是任何类型的 int、char 或 struct,例如节点

在上面的示例中,您更改了 head 指针寻址的值,并且 data 中的更改将被反映.

In the above example you change value at addressed by head pointer and change in data will be reflected.

但是假设您想在列表中更改 head 本身(例如,插入新节点作为第一个节点).

But suppose if you want to change head itself in your list (e.g. insert new node as first node).

void insert(node* head){
   head = malloc(sizeof(head));  // head changed 
   head->data = 10;
}

然后值不会在调用处反映出来,因为函数中的这个head与调用处的head不同.

Then value doesn't reflect at calling place because this head in function is not the same as head at calling place.

你有两种选择,要么return head,要么使用pointer to pointer(但记住只能返回一个值).

You have two choice, either return head or use pointer to pointer (but remember only one value can be return).

使用指针指向指针:

void insert(node** head){
   (*head) = malloc(sizeof **head);   
   (*head)->data = 10;
}

现在变化会反映出来!

重点是,如果地址是你的值(需要更新地址),那么你需要使用地址指针或者我应该说指向指针的指针来反映调用位置的变化.

The point is, if address is your value (need to updated address), then you need to use pointer of address or I should say pointer to pointer to reflect changes at the calling place.

因为您的问题是需要指针的指针,还有一个地方在 字符串数组动态二维数组,对于同样的用途,你可能需要指向指针的指针,例如 字符串或/3D字符数组的动态矩阵.

As your question is what is need of pointer to pointers, one more place where pointer to pointer used in array of string, and dynamic 2-D arrays, and for same use you may need pointer to pointer to pointer for example dynamic matrix of String or/ 3D char array.

另请阅读:Pointers to Pointers 我刚刚找到,给你举个例子.

Read also this:Pointers to Pointers I just found, to tell you for an example.

这篇关于需要指向指针的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆