转自:http://blog.csdn.net/sinat_20265495/article/details/51706355
帮同学解决了一个问题,自己从中也学到了东西,记下学习心得~~~
问题重现:
数组通过函数传递后为什么获取不到数组在内存中占用地址的长度?
![](https://img-blog.csdn.net/20160618185505890?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center)
在VS中编写如下的测试代码:
- #include "stdafx.h"
-
- void test(int b[])
- {
- int mm, nn;
- printf("%p", "%p", "%p\n", b, &b[0], &b);
- printf("\n");
- mm = sizeof(b);
- nn = sizeof(b[0]);
- int length_call = mm / nn;
- for (int i = 0; i < length_call; i++)
- {
- printf("%d\n", b[i]);
- }
- }
-
- int _tmain(int argc, _TCHAR* argv[])
- {
- int a[3] = {2,5,8};
- int m, n;
- printf("%p", "%p", "%p\n", a, &a[0], &a);
- printf("\n");
-
- m = sizeof(a);
- n = sizeof(a[0]);
- int length = m / n;
-
-
- for (int i = 0; i < length;i++)
- {
- printf("%d\n", a[i]);
- }
-
- printf("调用函数的输出结果:\n");
- test(a);
- return 0;
- }
输出结果:
![](https://img-blog.csdn.net/20160618190315031?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center)
通过调试过程中参数的变化理解了数组传参的本质:
(1)三个参数分别是数组、指针、数组指针;
、
(2)m和n分别为整形数组和整形变量在内存中占用的字节数;
![](https://img-blog.csdn.net/20160618191007555?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center)
(3)传入参数为数组;
![](https://img-blog.csdn.net/20160618191422561?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center)
(4)进入被调函数;
![](https://img-blog.csdn.net/20160618191558898?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center)
(5)三个参数分别为:指向传入数组首地址的指针、数组第一个元素的地址(即指针)、指针的地址;
![](https://img-blog.csdn.net/20160618191922552?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center)
(6)mm和nn分别为整形指针(不再是数组)和整形变量在内存中占用的字节数;
![](https://img-blog.csdn.net/20160618192503012?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center)
程序自然只能输出2咯~~
附:Sizeof关键字的使用总结
~~~~~~~~~~欢迎拍砖![害羞](http://static.blog.csdn.net/xheditor/xheditor_emot/default/shy.gif)
![害羞](http://static.blog.csdn.net/xheditor/xheditor_emot/default/shy.gif)
![害羞](http://static.blog.csdn.net/xheditor/xheditor_emot/default/shy.gif)