提及指针早已不再感觉到陌生,大一初识C语言,老师就一再强调指针的重要性。而然一直以来对其的认识仅停留在“指针:指向其他数据的内存位置的变量”。现在我们不妨以指针如何用开始,再次探究指针。
先来看一段代码:
#include<iostream>
using namespace std;
int main(){
int *p;
cout << p << endl;
return 0;
}
声明一个int型指针,不妨先看一下其里有什么?编译控制台打印:一串十六进制数值。不禁疑问这串十六进制数值是什么?
对编译原理有简单了解的都清楚,上述C++代码经过编译器,首先会编译为汇编代码,汇编代码大概如以下形式:
mov 8(%rsp), %rax;
int a = 10;
cout << &a << endl;
#include<iostream>
using namespace std;
int main(){
int *p;
cout << p << endl;
int a = 10;
cout << &a << endl;
p = &a;
cout << p << endl;
return 0;
}
#include<iostream>
using namespace std;
int main(){
int **pp;
cout << pp << endl;
int *p;
cout << &p << endl;
pp = &p;
cout << pp << endl;
return 0;
}
结论同上述一样。
#include<iostream>
using namespace std;
int main(){
int **pp;
cout << pp << endl;
int *p;
cout << &p << endl;//取p的地址
cout << p << endl;//打印p中的内容
pp = &p;
cout << pp << endl;//取pp中的内容
cout << *pp << endl;//取pp指向的内容
return 0;
}
上述代码,又添加了验证pp指向的内存空间的内容。此过程是否同计组原理中的间接寻址极为相似。通过上述分析,不难推断出指针的一般行为。
问题一:
存在整型变量a,以下等式是否成立?
a = *&a
不妨通过编译器试验一下:
if(x == *&x)
printf("yes\n");
else
printf("no\n");
#include<iostream>
using namespace std;
int main(){
char *p_char;
char c;
cout << sizeof(c) << "\t" << sizeof(p_char) << endl;
short *p_short;
short s;
cout << sizeof(s) << "\t" << sizeof(p_short) << endl;
int *p_int;
int i;
cout << sizeof(i) << "\t" << sizeof(p_int) << endl;
float *p_float;
float f;
cout << sizeof(f) << "\t" << sizeof(p_float) << endl;
double *p_double;
double d;
cout << sizeof(d) << "\t" << sizeof(p_double) << endl;
long *p_long;
long l;
cout << sizeof(l) << "\t" << sizeof(p_long) << endl;
long long *p_llong;
long long ll;
cout << sizeof(ll) << "\t" << sizeof(p_llong) << endl;
return 0;
}
#include<bits/stdc++.h>
using namespace std;
#define N 6
int main(){
int ars[N];
for(int i = 0; i < N; i++)
ars[i] = rand() % 10;
for(int i = 0; i < N; i++)
cout << ars[i] << " ";
cout << endl;
for(int i = 0; i < N; i++)
cout << *(ars + i) << " ";
return 0;
}
运行上述代码,可以发现两次打印内容相同。为什么会出现这种情况?
参考文献《深入理解计算机系统》
因篇幅问题不能全部显示,请点此查看更多更全内容