c,c++函數返回多個值的方法


最近遇到一個問題,需要通過一個函數返回多個值。無奈C,C++不能返回多個值。所以就想有什么方法可以解決。

網上方法比較雜亂,一般有兩種替代做法:

1. 利用函數的副作用, 返回值在函數外定義, 在函數內修改, 一般為void函數。

例1.1輸入x,y求修改后的x,y

 1 #include<iostream>
 2 using namespace std;
 3 void swap(int *p,int *q)
 4 {
 5     int temp;
 6     temp=*p;
 7     *p=*q;
 8     *q=temp;
 9 }
10 int main()
11 {
12 int a,b;
13 cin>>a>>b;
14 cout<<"the num is :"<<a<<b<<endl;
15 swap(a,b);//swap(&a,&b);
16 cout<<"the sorted num is :"<<a<<b<<endl;
17 }
View Code

例1.2輸入a,b,c求x,y,z

例1.3輸入x[]求修改后的x[]

 1 #include<stdio.h>
 2 #include<stdlib.h>
 3 void *bbb(int *p1)
 4 {
 5     int i=0;
 6     while(i<4)
 7     {
 8         *p1+=1;
 9         *p1++;
10         i++;
11     }
12 }
13 void main()
14 {
15     int a[4]={1,2,3,4};
16     bbb(a);
17     int i=0;
18     while(i<4)
19     {
20         printf("%d\t",a[i]);
21         i++;
22     }
23 }
View Code

例1.4輸入x[]求y[]

2. 把返回值打包返回,如返回一個數組名,指針,結構體.

例2.1返回一個數組名

#include<stdio.h>
#include<stdlib.h>
int *aaa(int a[])
{
    int i=0;
    while(i<4)
    {
        a[i]+=1;
        i++;
    }
    return a;
}
void main()
{
    int *p;
    int a[4]={1,2,3,4};
    p=aaa(a);
    int i=0;
    while(i<4)
    {
        printf("%d\t",a[i]);
        i++;
    }
}
View Code

例2.2返回一個指針

 1 #include<stdio.h>
 2 #include<stdlib.h>
 3 int aaa(int *p)
 4 {
 5     int i=0;
 6     while(i<4)
 7     {
 8         *p+++=1;
 9         i++;
10     }
11     return p;
12 }
13 void main()
14 {
15     int *px;
16     int a[4]={1,2,3,4};
17 
18     px=aaa(a);
19     int i=0;
20     while(i<4)
21     {
22         printf("%d\t",a[i]);
23         i++;
24     }
25 }
View Code

例2.3返回一個結構體

(被“略”的地方如果誰有興趣可以自己去試着寫一個)

帶返回值的函數需要用一個指針接受,而接收的也是之前主函數里定義的變量的地址。即只要函數被調用了,變量的值就改變了,根本不需要在定義一個指針變量來接收,從這可以得出,有返回值的函數都可以改成void()型函數。(即例2.2可以簡寫成例1.3)

綜上

可以看出,無論你怎么返回,無論你返回不返回,幾乎都需要用到指針。可能有人會說用純數組也可也實現,LZ以前也用數組,但現在覺得以前很愚蠢,原因會用指針的人都知道吧。其實上面的眾多方法說白了也就一句話:

利用指針。

指針很強大,LZ以前貪玩,沒怎么學,最近學C,又撿起來看了一下,一定要把這個學會。用好。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM