(原創) 如何讓pointer指向pointer自己? (C/C++) (C)
Abstract
在小明思考 的{Just for fun} 如何让指针指向自己 ,他用了C++寫了這個有趣的題目,我用C語言改寫了一次。
Introduction
題目很簡單,有一個pointer,希望他指的是自己這個pointer,也就是最後希望cout << &p << endl和cout << p << 結果一樣。
原作用C++的template function來做
1/*
2(C) OOMusou 2007 http://oomusou.cnblogs.com
3
4Filename : pointer2self_CPP.cpp
5Compiler : Visual C++ 8.0 / BCB 6.0 / gcc 3.4.2 / ISO C++
6Description : Demo how to point to pointer itself
7Release : 05/24/2007 1.0
8*/
9#include <iostream>
10
11using namespace std;
12
13template <typename T>
14inline void p2self(T* &p) {
15 p = (T*)&p;
16}
17
18int main() {
19 int *pi;
20 cout << &pi << endl;
21
22 p2self(pi);
23
24 cout << pi << endl;
25}
2(C) OOMusou 2007 http://oomusou.cnblogs.com
3
4Filename : pointer2self_CPP.cpp
5Compiler : Visual C++ 8.0 / BCB 6.0 / gcc 3.4.2 / ISO C++
6Description : Demo how to point to pointer itself
7Release : 05/24/2007 1.0
8*/
9#include <iostream>
10
11using namespace std;
12
13template <typename T>
14inline void p2self(T* &p) {
15 p = (T*)&p;
16}
17
18int main() {
19 int *pi;
20 cout << &pi << endl;
21
22 p2self(pi);
23
24 cout << pi << endl;
25}
執行結果
0012FF60
0012FF60
0012FF60
這個程式相當好懂,由於C++多了reference,所以可以少用一個pointer,最後再用泛型的(T*)轉成原本型別的pointer。
若用C語言寫,由於要處理各種型別的pointer,有兩種方法,一種使用macro,一種使用void*
1/*
2(C) OOMusou 2007 http://oomusou.cnblogs.com
3
4Filename : pointer2self_C.cpp
5Compiler : Visual C++ 8.0 / BCB 6.0 / gcc 3.4.2 / ISO C++
6Description : Demo how to point to pointer itself
7Release : 05/24/2007 1.0
8*/
9#include "stdio.h"
10
11//#define p2self(p) (*p) = (void*)&(*p)
12void p2self(void** p) {
13 (*p) = (void*)&(*p);
14}
15
16int main() {
17 int* pi;
18 printf("%x\n",&pi);
19
20 p2self((void**)&pi);
21
22 printf("%x\n",pi);
23}
2(C) OOMusou 2007 http://oomusou.cnblogs.com
3
4Filename : pointer2self_C.cpp
5Compiler : Visual C++ 8.0 / BCB 6.0 / gcc 3.4.2 / ISO C++
6Description : Demo how to point to pointer itself
7Release : 05/24/2007 1.0
8*/
9#include "stdio.h"
10
11//#define p2self(p) (*p) = (void*)&(*p)
12void p2self(void** p) {
13 (*p) = (void*)&(*p);
14}
15
16int main() {
17 int* pi;
18 printf("%x\n",&pi);
19
20 p2self((void**)&pi);
21
22 printf("%x\n",pi);
23}
執行結果
0012FF60
0012FF60
0012FF60
11行
#define p2self(p) (*p) = (void*)&(*p)
使用的是macro
12行
void p2self(void** p) {
(*p) = (void*)&(*p);
}
(*p) = (void*)&(*p);
}
使用的是void*
為什麼是void**呢?原本是int*,為了處理所有型別的pointer變成void*,為了使pointer用pass by reference傳遞,所以多了一個pointer變成void **。
Conclusion
這沒什麼實際的用途,誠如原作者所說,just for fun,但看到了function template如何用macro或void*來實做,但若以可讀性來說,可以看出C++還是比C語言可讀性來的高。
Reference
{Just for fun} 如何让指针指向自己