Trong C, con trỏ trỏ tới con trỏ (double pointer) là biến chứa địa chỉ của một con trỏ khác.
Khai báo
kiểu_dữ_liệu ** tên_con_trỏ;
Ví dụ: int **p; – p là con trỏ trỏ tới con trỏ.
Khởi tạo
Sử dụng toán tử & để khởi tạo.
Ví dụ:
int a = 10; int *p; int **q; p = &a;
Truy cập
Sử dụng toán tử gián tiếp * để truy cập.
Chương trình mẫu
Chương trình C minh họa double pointer:
#include<stdio.h> main ( ){ int a = 10; int *p; int **q; p = &a; q = &p; printf("a =%d ",a); printf(" a value through pointer = %d", *p); printf(" a value through pointer to pointer = %d", **q); }
Kết quả
a=10 a value through pointer = 10 a value through pointer to pointer = 10
Ví dụ khác
Chương trình thể hiện mối quan hệ giữa con trỏ trỏ tới con trỏ:
#include<stdio.h> void main(){ //Khai báo biến và con trỏ// int a=10; int *p; p=&a; int **q; q=&p; //In kết quả// printf("Value of a is %d\n",a);//10// printf("Address location of a is %d\n",p);//địa chỉ a// printf("Value of p which is address location of a is %d\n",*p);//10// printf("Address location of p is %d\n",q);//địa chỉ p// printf("Value at address location q(which is address location of p) is %d\n",*q);//địa chỉ a// printf("Value at address location p(which is address location of a) is %d\n",**q);//10// }
Kết quả
Value of a is 10 Address location of a is 6422036 Value of p which is address location of a is 10 Address location of p is 6422024 Value at address location q(which is address location of p) is 6422036 Value at address location p(which is address location of a) is 10