数组名、指针和地址
首先看这个:
#include <stdio.h> #include <iostream> using namespace std; int main() { int a[2] = {1, 2}; cout << "The address of int_array: " << endl; cout << a << " " << &a << endl << endl; double b[2] = {1.2, 1.3}; cout << "The address of double_array: " << endl; cout << b << " " << &b << endl << endl; char c[2] = {'a', 'b'}; cout << "The address of char_array: " << endl; cout << c << " " << &c << endl << endl; int d[5] = {1, 2, 3, 4, 5}; int dd[5] = {6, 7, 8, 9, 0}; int j = 2, k = 1, i = 3; cout << d[i] << " " << i[d] << endl << endl; //this code is so strange, but in fact, d[i] = *(d + i) = *(i + d) = i[d]. return 0; }
#include <stdio.h> int main() { int a[5] = {1, 2, 3, 4, 5}; printf("a = %p\n", a); printf("&a = %p\n", &a); printf("a + 1 = %p\n", a + 1); printf("&a + 1 = %p\n", &a + 1); return 0; }
#include <iostream> using namespace std; int main() { int a[5] = {305210130, 1164203589, 2023197048, 4, 5};//前三个数字在十六进制中表示分别是12312312、45645645、78978978,这样写主要为了测试方便 int *ptr1 = (int *)(&a + 1); int *ptr2 = (int *)((int)a + 1); for (int i = 0; i < 20; i++) {//01 cout << hex << *(int *)((int)a + i) << dec << ' '; } cout << endl << endl; cout << "&a + 1 : " << &a + 1 << endl;//02 cout << "*(&a + 1) : " << *(&a + 1) << endl;//03 cout << "**(&a + 1) : " << **(&a + 1) << endl;//04 cout << "*(a + 5) : " << *(a + 5) << endl;//05 cout << "(int *)(&a + 1) : " << (int *)(&a + 1) << endl;//06 cout << "*((int *)(&a + 1)) : " << *((int *)(&a + 1))<< endl;//07 cout << "*ptr1 : " << *ptr1 << endl;//08 cout << "ptr1 : " << ptr1 << endl;//09 cout << "ptr1[-1] : " << ptr1[-1] << endl;//10 cout << "ptr1[-5] : " << ptr1[-5] << endl;//11 cout << "(int)a : " << (int)a << endl;//12 cout << "(int)a + 1 : " << (int)a + 1 << endl;//13 cout << "(int *)((int)a + 1) : " << (int *)((int)a + 1) << endl;//14 cout << "the address of a's first element : " << a << endl;//15 cout << "*ptr2 : " << *ptr2 << endl;//16 cout << "ptr2 : " << ptr2 << endl;//17 cout << "the hex of *ptr2(*ptr2 = (int *)((int)a + 1)) : " << hex << *ptr2 << dec << endl;//18 ptr2 = (int *)((int)a + 3);//19 cout << "the hex of *ptr2(*ptr2 = (int *)((int)a + 3)) : " << hex << *ptr2 << dec << endl;//20 return 0; }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。