函数体中用指针返回数组的方法

今天上机过程中无意发现的问题

题目是用函数统计一组数据中低于平均数的 人的个数n 并返回 低于平均分的 分数的数组a[]

不是难题,我一开始写的时候是建一个和原数据相同大小的数组,加入n个数据后输出到n就可以了。

旁边的同学问我的时候想到一个新的方法来返回数组:

传入指针记录下数组a的首地址;

主函数中 cout<<*a++;

简单代码如下(与题目无关):

 1 #include<iostream>
 2 using namespace std;
 3 void fun(int *p)
 4 { 
 5     int *a=new int[5];
 6     for(int i=0;i<5;i++)
          a[i]=i;
7 p=a; 8 } 9 int main() 10 { 11 int *p; 12 fun(p); 13 for(int i=0;i<5;i++) 14 cout<<*p++<<endl; 15 return 0; 16 }

程序编译不会出错,运行就会溢出。

逻辑上感觉都对,后来想了一下,因为此指针只被赋了数组的首地址,本身并不具有数组的特性,所以p++是没有含义的。

用这样的方法去返回数组的话需要传出指针的地址,让指针记录数组的地址,修改如下:

 1 #include<iostream>
 2 using namespace std;
 3 void fun(int **p)
 4 { 
 5     int *a=new int[5];
 6     for(int i=0;i<5;i++)
 7         a[i]=i;
 8     *p=a;
 9 }
10 int main()
11 {
12     int *p;
13     fun(&p);
14     for(int i=0;i<5;i++)
15         cout<<*p++<<endl;
16     return 0;
17 }
原文地址:https://www.cnblogs.com/verlen11/p/4184423.html