zoukankan      html  css  js  c++  java
  • 数组名VS数组名取地址

    实验准备:

    我们使用VC++6.0进行实验,首先需要打开VC++6.0的RTTI选项(默认关闭)

    Project->settings->c/c++->category->c++language,Enable Run-Time TypeInfomation(RTTI)选中


    测试代码:

    #include <iostream>
    
    using namespace std;
    
    int main()
    {
    	int array[3] = {2, 4, 6};
    	typedef int (*ARRAY)[3];
    	int *p = array;
    	ARRAY q = &array;
    	//int *q = &array; //编译错误
    	cout << "p = " << p << "\t\t" << typeid(p).name() << endl;
    	cout << "q = " << q << "\t\t" << typeid(q).name() << endl;
    	cout << "array = " << array << "\t\t" << typeid(array).name() << endl;
    	cout << "&array = " << &array << "\t\t" << typeid(&array).name() << endl;
    	cout << "*(p+1) = " << *(p + 1) << "\t\t" << typeid(*(p + 1)).name() << endl;
    	cout << "*(q+1) = " << *(q + 1) << "\t\t" << typeid(*(q + 1)).name() << endl;
    	cout << "*p+1 = " << *p + 1 << "\t\t" << typeid(*p + 1).name() << endl;
    	cout << "*q+1 = " << *q + 1 << "\t\t" << typeid(*q + 1).name() << endl;
    	cout << "*(*q+1) = " << *(*q + 1) << "\t\t" << typeid(*(*q + 1)).name() << endl;
    	cout << "p+1 = " << p + 1 << "\t\t" << typeid(p + 1).name() << endl;
    	cout << "q+1 = " << q + 1 << "\t\t" << typeid(q + 1).name() << endl;
    	return 0;
    }

    测试结果:


    实验结论:

    1.      p和q的值相同,即array和&array是相同的,均指向相同的地址,但是两个指针的类型不同,p(array)的类型是int *(整型指针),而q(&array)的类型是int (*)[3](数组指针),这也是语句“int *q = &array;”错误的原因

    2.      因为p是int *类型的指针,故p+1=0018FF40,即每次+1,地址+4,指向数组中下一个数据;而q是int (*)[3]类型的指针,故q+1=0018FF48,即每次+1,地址+12(3*4),指向下一个数组

    3.      *(p+1)==p[1]==array[1]==4,这很好理解;而按照相同的逻辑,*(q+1)==q[1]==(&array)[1],此时我们可以理解成“在内存中有一个更大的数组,其元素的类型为int [3],故q[1]就等价于指向这个大数组中的第二个元素”,根据2的解释,我们知道“第二个元素”的地址为0018FF48

    4.      *p+1很简单,*p就是array数组中第一个元素,*p+1即将2加1,得3;而由恒等式*&x==x知,*q=*&array=array,即*q就是数组中第一个元素的地址,*q+1即将0018FF3C加1(指针+1等价地址+4),得0018FF40,此时*q+1的类型为int*,故对*q+1进行解引用(*)就是地址所指值,故*(*q+1)==array[1]==4

    实验图解:


  • 相关阅读:
    LeetCode 1122. Relative Sort Array (数组的相对排序)
    LeetCode 46. Permutations (全排列)
    LeetCode 47. Permutations II (全排列 II)
    LeetCode 77. Combinations (组合)
    LeetCode 1005. Maximize Sum Of Array After K Negations (K 次取反后最大化的数组和)
    LeetCode 922. Sort Array By Parity II (按奇偶排序数组 II)
    LeetCode 1219. Path with Maximum Gold (黄金矿工)
    LeetCode 1029. Two City Scheduling (两地调度)
    LeetCode 392. Is Subsequence (判断子序列)
    写程序判断系统是大端序还是小端序
  • 原文地址:https://www.cnblogs.com/javawebsoa/p/3031599.html
Copyright © 2011-2022 走看看